xref: /illumos-gate/usr/src/uts/common/io/scsi/targets/st.c (revision c6914c10632dbf46820663057266b1f3a8b26276)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 #pragma ident	"%Z%%M%	%I%	%E% SMI"
28 
29 /*
30  * SCSI	 SCSA-compliant and not-so-DDI-compliant Tape Driver
31  */
32 
33 #if defined(lint) && !defined(DEBUG)
34 #define	DEBUG	1
35 #endif
36 
37 #include <sys/modctl.h>
38 #include <sys/scsi/scsi.h>
39 #include <sys/mtio.h>
40 #include <sys/scsi/targets/stdef.h>
41 #include <sys/file.h>
42 #include <sys/kstat.h>
43 #include <sys/ddidmareq.h>
44 #include <sys/ddi.h>
45 #include <sys/sunddi.h>
46 
47 #define	IOSP	KSTAT_IO_PTR(un->un_stats)
48 /*
49  * stats maintained only for reads/writes as commands
50  * like rewind etc skew the wait/busy times
51  */
52 #define	IS_RW(bp) 	((bp)->b_bcount > 0)
53 #define	ST_DO_KSTATS(bp, kstat_function) \
54 	if ((bp != un->un_sbufp) && un->un_stats && IS_RW(bp)) { \
55 		kstat_function(IOSP); \
56 	}
57 
58 #define	ST_DO_ERRSTATS(un, x)  \
59 	if (un->un_errstats) { \
60 		struct st_errstats *stp; \
61 		stp = (struct st_errstats *)un->un_errstats->ks_data; \
62 		stp->x.value.ul++; \
63 	}
64 
65 #define	FILL_SCSI1_LUN(devp, pkt) 					\
66 	if ((devp)->sd_inq->inq_ansi == 0x1) {				\
67 		int _lun;						\
68 		_lun = ddi_prop_get_int(DDI_DEV_T_ANY, (devp)->sd_dev,	\
69 		    DDI_PROP_DONTPASS, SCSI_ADDR_PROP_LUN, 0);		\
70 		if (_lun > 0) {						\
71 			((union scsi_cdb *)(pkt)->pkt_cdbp)->scc_lun =	\
72 			    _lun;					\
73 		}							\
74 	}
75 
76 /*
77  * get an available contig mem header, cp.
78  * when big_enough is true, we will return NULL, if no big enough
79  * contig mem is found.
80  * when big_enough is false, we will try to find cp containing big
81  * enough contig mem. if not found, we will ruturn the last cp available.
82  *
83  * used by st_get_contig_mem()
84  */
85 #define	ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough) {		\
86 	struct contig_mem *tmp_cp = NULL;				\
87 	for ((cp) = (un)->un_contig_mem;				\
88 	    (cp) != NULL;						\
89 	    tmp_cp = (cp), (cp) = (cp)->cm_next) { 			\
90 		if (((cp)->cm_len >= (len)) || 				\
91 		    (!(big_enough) && ((cp)->cm_next == NULL))) { 	\
92 			if (tmp_cp == NULL) { 				\
93 				(un)->un_contig_mem = (cp)->cm_next; 	\
94 			} else { 					\
95 				tmp_cp->cm_next = (cp)->cm_next; 	\
96 			} 						\
97 			(cp)->cm_next = NULL; 				\
98 			(un)->un_contig_mem_available_num--; 		\
99 			break; 						\
100 		} 							\
101 	} 								\
102 }
103 
104 #define	ST_NUM_MEMBERS(array)	(sizeof (array) / sizeof (array[0]))
105 #define	COPY_POS(dest, source) bcopy(source, dest, sizeof (tapepos_t))
106 
107 #define	ONE_K	1024
108 
109 /*
110  * Global External Data Definitions
111  */
112 extern struct scsi_key_strings scsi_cmds[];
113 extern uchar_t	scsi_cdb_size[];
114 
115 /*
116  * Local Static Data
117  */
118 static void *st_state;
119 static char *const st_label = "st";
120 
121 #if defined(__i386) || defined(__amd64)
122 /*
123  * We need to use below DMA attr to alloc physically contiguous
124  * memory to do I/O in big block size
125  */
126 static ddi_dma_attr_t st_contig_mem_dma_attr = {
127 	DMA_ATTR_V0,    /* version number */
128 	0x0,		/* lowest usable address */
129 	0xFFFFFFFFull,  /* high DMA address range */
130 	0xFFFFFFFFull,  /* DMA counter register */
131 	1,		/* DMA address alignment */
132 	1,		/* DMA burstsizes */
133 	1,		/* min effective DMA size */
134 	0xFFFFFFFFull,  /* max DMA xfer size */
135 	0xFFFFFFFFull,  /* segment boundary */
136 	1,		/* s/g list length */
137 	1,		/* granularity of device */
138 	0		/* DMA transfer flags */
139 };
140 
141 static ddi_device_acc_attr_t st_acc_attr = {
142 	DDI_DEVICE_ATTR_V0,
143 	DDI_NEVERSWAP_ACC,
144 	DDI_STRICTORDER_ACC
145 };
146 
147 /* set limitation for the number of contig_mem */
148 static int st_max_contig_mem_num = ST_MAX_CONTIG_MEM_NUM;
149 #endif
150 
151 /*
152  * Tunable parameters
153  *
154  * DISCLAIMER
155  * ----------
156  * These parameters are intended for use only in system testing; if you use
157  * them in production systems, you do so at your own risk. Altering any
158  * variable not listed below may cause unpredictable system behavior.
159  *
160  * st_check_media_time
161  *
162  *   Three second state check
163  *
164  * st_allow_large_xfer
165  *
166  *   Gated with ST_NO_RECSIZE_LIMIT
167  *
168  *   0 - Transfers larger than 64KB will not be allowed
169  *       regardless of the setting of ST_NO_RECSIZE_LIMIT
170  *   1 - Transfers larger than 64KB will be allowed
171  *       if ST_NO_RECSIZE_LIMIT is TRUE for the drive
172  *
173  * st_report_soft_errors_on_close
174  *
175  *  Gated with ST_SOFT_ERROR_REPORTING
176  *
177  *  0 - Errors will not be reported on close regardless
178  *      of the setting of ST_SOFT_ERROR_REPORTING
179  *
180  *  1 - Errors will be reported on close if
181  *      ST_SOFT_ERROR_REPORTING is TRUE for the drive
182  */
183 static int st_selection_retry_count = ST_SEL_RETRY_COUNT;
184 static int st_retry_count	= ST_RETRY_COUNT;
185 
186 static int st_io_time		= ST_IO_TIME;
187 static int st_long_timeout_x	= ST_LONG_TIMEOUT_X;
188 
189 static int st_space_time	= ST_SPACE_TIME;
190 static int st_long_space_time_x	= ST_LONG_SPACE_TIME_X;
191 
192 static int st_error_level	= SCSI_ERR_RETRYABLE;
193 static int st_check_media_time	= 3000000;	/* 3 Second State Check */
194 
195 static int st_max_throttle	= ST_MAX_THROTTLE;
196 
197 static clock_t st_wait_cmds_complete = ST_WAIT_CMDS_COMPLETE;
198 
199 static int st_allow_large_xfer = 1;
200 static int st_report_soft_errors_on_close = 1;
201 
202 /*
203  * End of tunable parameters list
204  */
205 
206 
207 
208 /*
209  * Asynchronous I/O and persistent errors, refer to PSARC/1995/228
210  *
211  * Asynchronous I/O's main offering is that it is a non-blocking way to do
212  * reads and writes.  The driver will queue up all the requests it gets and
213  * have them ready to transport to the HBA.  Unfortunately, we cannot always
214  * just ship the I/O requests to the HBA, as there errors and exceptions
215  * that may happen when we don't want the HBA to continue.  Therein comes
216  * the flush-on-errors capability.  If the HBA supports it, then st will
217  * send in st_max_throttle I/O requests at the same time.
218  *
219  * Persistent errors : This was also reasonably simple.  In the interrupt
220  * routines, if there was an error or exception (FM, LEOT, media error,
221  * transport error), the persistent error bits are set and shuts everything
222  * down, but setting the throttle to zero.  If we hit and exception in the
223  * HBA, and flush-on-errors were set, we wait for all outstanding I/O's to
224  * come back (with CMD_ABORTED), then flush all bp's in the wait queue with
225  * the appropriate error, and this will preserve order. Of course, depending
226  * on the exception we have to show a zero read or write before we show
227  * errors back to the application.
228  */
229 
230 extern const int st_ndrivetypes;	/* defined in st_conf.c */
231 extern const struct st_drivetype st_drivetypes[];
232 extern const char st_conf_version[];
233 
234 #ifdef STDEBUG
235 static int st_soft_error_report_debug = 0;
236 volatile int st_debug = 0;
237 #endif
238 
239 #define	ST_MT02_NAME	"Emulex  MT02 QIC-11/24  "
240 
241 static const struct driver_minor_data {
242 	char	*name;
243 	int	minor;
244 } st_minor_data[] = {
245 	/*
246 	 * The top 4 entries are for the default densities,
247 	 * don't alter their position.
248 	 */
249 	{"",	0},
250 	{"n",	MT_NOREWIND},
251 	{"b",	MT_BSD},
252 	{"bn",	MT_NOREWIND | MT_BSD},
253 	{"l",	MT_DENSITY1},
254 	{"m",	MT_DENSITY2},
255 	{"h",	MT_DENSITY3},
256 	{"c",	MT_DENSITY4},
257 	{"u",	MT_DENSITY4},
258 	{"ln",	MT_DENSITY1 | MT_NOREWIND},
259 	{"mn",	MT_DENSITY2 | MT_NOREWIND},
260 	{"hn",	MT_DENSITY3 | MT_NOREWIND},
261 	{"cn",	MT_DENSITY4 | MT_NOREWIND},
262 	{"un",	MT_DENSITY4 | MT_NOREWIND},
263 	{"lb",	MT_DENSITY1 | MT_BSD},
264 	{"mb",	MT_DENSITY2 | MT_BSD},
265 	{"hb",	MT_DENSITY3 | MT_BSD},
266 	{"cb",	MT_DENSITY4 | MT_BSD},
267 	{"ub",	MT_DENSITY4 | MT_BSD},
268 	{"lbn",	MT_DENSITY1 | MT_NOREWIND | MT_BSD},
269 	{"mbn",	MT_DENSITY2 | MT_NOREWIND | MT_BSD},
270 	{"hbn",	MT_DENSITY3 | MT_NOREWIND | MT_BSD},
271 	{"cbn",	MT_DENSITY4 | MT_NOREWIND | MT_BSD},
272 	{"ubn",	MT_DENSITY4 | MT_NOREWIND | MT_BSD}
273 };
274 
275 /* strings used in many debug and warning messages */
276 static const char wr_str[]  = "write";
277 static const char rd_str[]  = "read";
278 static const char wrg_str[] = "writing";
279 static const char rdg_str[] = "reading";
280 static const char *space_strs[] = {
281 	"records",
282 	"filemarks",
283 	"sequential filemarks",
284 	"eod",
285 	"setmarks",
286 	"sequential setmarks",
287 	"Reserved",
288 	"Reserved"
289 };
290 
291 /* default density offsets in the table above */
292 #define	DEF_BLANK	0
293 #define	DEF_NOREWIND	1
294 #define	DEF_BSD		2
295 #define	DEF_BSD_NR	3
296 
297 /* Sense Key, ASC/ASCQ for which tape ejection is needed */
298 
299 static struct tape_failure_code {
300 	uchar_t key;
301 	uchar_t add_code;
302 	uchar_t qual_code;
303 } st_tape_failure_code[] = {
304 	{ KEY_HARDWARE_ERROR, 0x15, 0x01},
305 	{ KEY_HARDWARE_ERROR, 0x44, 0x00},
306 	{ KEY_HARDWARE_ERROR, 0x53, 0x00},
307 	{ KEY_HARDWARE_ERROR, 0x53, 0x01},
308 	{ KEY_NOT_READY, 0x53, 0x00},
309 	{ 0xff}
310 };
311 
312 /*  clean bit position and mask */
313 
314 static struct cln_bit_position {
315 	ushort_t cln_bit_byte;
316 	uchar_t cln_bit_mask;
317 } st_cln_bit_position[] = {
318 	{ 21, 0x08},
319 	{ 70, 0xc0},
320 	{ 18, 0x81}  /* 80 bit indicates in bit mode, 1 bit clean light is on */
321 };
322 
323 /*
324  * architecture dependent allocation restrictions. For x86, we'll set
325  * dma_attr_addr_hi to st_max_phys_addr and dma_attr_sgllen to
326  * st_sgl_size during _init().
327  */
328 #if defined(__sparc)
329 static ddi_dma_attr_t st_alloc_attr = {
330 	DMA_ATTR_V0,	/* version number */
331 	0x0,		/* lowest usable address */
332 	0xFFFFFFFFull,	/* high DMA address range */
333 	0xFFFFFFFFull,	/* DMA counter register */
334 	1,		/* DMA address alignment */
335 	1,		/* DMA burstsizes */
336 	1,		/* min effective DMA size */
337 	0xFFFFFFFFull,	/* max DMA xfer size */
338 	0xFFFFFFFFull,	/* segment boundary */
339 	1,		/* s/g list length */
340 	512,		/* granularity of device */
341 	0		/* DMA transfer flags */
342 };
343 #elif defined(__x86)
344 static ddi_dma_attr_t st_alloc_attr = {
345 	DMA_ATTR_V0,	/* version number */
346 	0x0,		/* lowest usable address */
347 	0x0,		/* high DMA address range [set in _init()] */
348 	0xFFFFull,	/* DMA counter register */
349 	512,		/* DMA address alignment */
350 	1,		/* DMA burstsizes */
351 	1,		/* min effective DMA size */
352 	0xFFFFFFFFull,	/* max DMA xfer size */
353 	0xFFFFFFFFull,  /* segment boundary */
354 	0,		/* s/g list length */
355 	512,		/* granularity of device [set in _init()] */
356 	0		/* DMA transfer flags */
357 };
358 uint64_t st_max_phys_addr = 0xFFFFFFFFull;
359 int st_sgl_size = 0xF;
360 
361 #endif
362 
363 /*
364  * Configuration Data:
365  *
366  * Device driver ops vector
367  */
368 static int st_aread(dev_t dev, struct aio_req *aio, cred_t *cred_p);
369 static int st_awrite(dev_t dev, struct aio_req *aio, cred_t *cred_p);
370 static int st_read(dev_t  dev,  struct   uio   *uio_p,   cred_t *cred_p);
371 static int st_write(dev_t  dev,  struct  uio   *uio_p,   cred_t *cred_p);
372 static int st_open(dev_t  *devp,  int  flag,  int  otyp,  cred_t *cred_p);
373 static int st_close(dev_t  dev,  int  flag,  int  otyp,  cred_t *cred_p);
374 static int st_strategy(struct buf *bp);
375 static int st_ioctl(dev_t dev, int cmd, intptr_t arg, int  flag,
376 	cred_t *cred_p, int *rval_p);
377 extern int nulldev(), nodev();
378 
379 static struct cb_ops st_cb_ops = {
380 	st_open,		/* open */
381 	st_close,		/* close */
382 	st_strategy,		/* strategy */
383 	nodev,			/* print */
384 	nodev,			/* dump */
385 	st_read,		/* read */
386 	st_write,		/* write */
387 	st_ioctl,		/* ioctl */
388 	nodev,			/* devmap */
389 	nodev,			/* mmap */
390 	nodev,			/* segmap */
391 	nochpoll,		/* poll */
392 	ddi_prop_op,		/* cb_prop_op */
393 	0,			/* streamtab  */
394 	D_64BIT | D_MP | D_NEW | D_HOTPLUG |
395 	D_OPEN_RETURNS_EINTR,	/* cb_flag */
396 	CB_REV,			/* cb_rev */
397 	st_aread, 		/* async I/O read entry point */
398 	st_awrite		/* async I/O write entry point */
399 
400 };
401 
402 static int stinfo(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg,
403 		void **result);
404 static int st_probe(dev_info_t *dev);
405 static int st_attach(dev_info_t *dev, ddi_attach_cmd_t cmd);
406 static int st_detach(dev_info_t *dev, ddi_detach_cmd_t cmd);
407 
408 static struct dev_ops st_ops = {
409 	DEVO_REV,		/* devo_rev, */
410 	0,			/* refcnt  */
411 	stinfo,			/* info */
412 	nulldev,		/* identify */
413 	st_probe,		/* probe */
414 	st_attach,		/* attach */
415 	st_detach,		/* detach */
416 	nodev,			/* reset */
417 	&st_cb_ops,		/* driver operations */
418 	(struct bus_ops *)0,	/* bus operations */
419 	nulldev			/* power */
420 };
421 
422 /*
423  * Local Function Declarations
424  */
425 static char *st_print_scsi_cmd(char cmd);
426 static void st_print_cdb(dev_info_t *dip, char *label, uint_t level,
427     char *title, char *cdb);
428 static void st_clean_print(dev_info_t *dev, char *label, uint_t level,
429 	char *title, char *data, int len);
430 static int st_doattach(struct scsi_device *devp, int (*canwait)());
431 static void st_known_tape_type(struct scsi_tape *un);
432 static int st_get_conf_from_st_dot_conf(struct scsi_tape *, char *,
433     struct st_drivetype *);
434 static int st_get_conf_from_st_conf_dot_c(struct scsi_tape *, char *,
435     struct st_drivetype *);
436 static int st_get_default_conf(struct scsi_tape *, char *,
437     struct st_drivetype *);
438 static int st_rw(dev_t dev, struct uio *uio, int flag);
439 static int st_arw(dev_t dev, struct aio_req *aio, int flag);
440 static int st_find_eod(dev_t dev);
441 static int st_check_density_or_wfm(dev_t dev, int wfm, int mode, int stepflag);
442 static int st_ioctl_cmd(dev_t dev, struct uscsi_cmd *, int flag);
443 static int st_mtioctop(struct scsi_tape *un, intptr_t arg, int flag);
444 static int st_mtiocltop(struct scsi_tape *un, intptr_t arg, int flag);
445 static int st_do_mtioctop(struct scsi_tape *un, struct mtlop *mtop);
446 static void st_start(struct scsi_tape *un);
447 static int st_handle_start_busy(struct scsi_tape *un, struct buf *bp,
448     clock_t timeout_interval);
449 static int st_handle_intr_busy(struct scsi_tape *un, struct buf *bp,
450     clock_t timeout_interval);
451 static int st_handle_intr_retry_lcmd(struct scsi_tape *un, struct buf *bp);
452 static void st_done_and_mutex_exit(struct scsi_tape *un, struct buf *bp);
453 static void st_init(struct scsi_tape *un);
454 static void st_make_cmd(struct scsi_tape *un, struct buf *bp,
455     int (*func)(caddr_t));
456 static void st_make_uscsi_cmd(struct scsi_tape *, struct uscsi_cmd *,
457     struct buf *bp, int (*func)(caddr_t));
458 static void st_intr(struct scsi_pkt *pkt);
459 static void st_set_state(struct scsi_tape *un);
460 static void st_test_append(struct buf *bp);
461 static int st_runout(caddr_t);
462 static int st_cmd(dev_t dev, int com, int count, int wait);
463 static int st_set_compression(struct scsi_tape *un);
464 static int st_write_fm(dev_t dev, int wfm);
465 static int st_determine_generic(dev_t dev);
466 static int st_determine_density(dev_t dev, int rw);
467 static int st_get_density(dev_t dev);
468 static int st_set_density(dev_t dev);
469 static int st_loadtape(dev_t dev);
470 static int st_modesense(struct scsi_tape *un);
471 static int st_modeselect(struct scsi_tape *un);
472 static int st_handle_incomplete(struct scsi_tape *un, struct buf *bp);
473 static int st_wrongtapetype(struct scsi_tape *un);
474 static int st_check_error(struct scsi_tape *un, struct scsi_pkt *pkt);
475 static int st_handle_sense(struct scsi_tape *un, struct buf *bp);
476 static int st_handle_autosense(struct scsi_tape *un, struct buf *bp);
477 static int st_decode_sense(struct scsi_tape *un, struct buf *bp, int amt,
478 	struct scsi_status *);
479 static int st_report_soft_errors(dev_t dev, int flag);
480 static void st_delayed_cv_broadcast(void *arg);
481 static int st_check_media(dev_t dev, enum mtio_state state);
482 static int st_media_watch_cb(caddr_t arg, struct scsi_watch_result *resultp);
483 static void st_intr_restart(void *arg);
484 static void st_start_restart(void *arg);
485 static int st_gen_mode_sense(struct scsi_tape *un, int page,
486     struct seq_mode *page_data, int page_size);
487 static int st_change_block_size(dev_t dev, uint32_t nblksz);
488 static int st_gen_mode_select(struct scsi_tape *un, struct seq_mode *page_data,
489     int page_size);
490 static int st_tape_init(dev_t dev);
491 static void st_flush(struct scsi_tape *un);
492 static void st_set_pe_errno(struct scsi_tape *un);
493 static void st_hba_unflush(struct scsi_tape *un);
494 static void st_turn_pe_on(struct scsi_tape *un);
495 static void st_turn_pe_off(struct scsi_tape *un);
496 static void st_set_pe_flag(struct scsi_tape *un);
497 static void st_clear_pe(struct scsi_tape *un);
498 static void st_wait_for_io(struct scsi_tape *un);
499 static int st_set_devconfig_page(struct scsi_tape *un, int compression_on);
500 static int st_set_datacomp_page(struct scsi_tape *un, int compression_on);
501 static int st_reserve_release(struct scsi_tape *un, int command);
502 static int st_check_cdb_for_need_to_reserve(struct scsi_tape *un, caddr_t cdb);
503 static int st_check_cmd_for_need_to_reserve(struct scsi_tape *un, uchar_t cmd,
504     int count);
505 static int st_take_ownership(dev_t dev);
506 static int st_check_asc_ascq(struct scsi_tape *un);
507 static int st_check_clean_bit(dev_t dev);
508 static int st_check_alert_flags(dev_t dev);
509 static int st_check_sequential_clean_bit(dev_t dev);
510 static int st_check_sense_clean_bit(dev_t dev);
511 static int st_clear_unit_attentions(dev_t dev_instance, int max_trys);
512 static void st_calculate_timeouts(struct scsi_tape *un);
513 static writablity st_is_drive_worm(struct scsi_tape *un);
514 static int st_read_attributes(struct scsi_tape *un, uint16_t attribute,
515     caddr_t buf, size_t size);
516 static int st_get_special_inquiry(struct scsi_tape *un, uchar_t size,
517     caddr_t dest, uchar_t page);
518 static int st_update_block_pos(struct scsi_tape *un);
519 static int st_interpret_read_pos(struct scsi_tape *un, read_p_types type,
520     size_t data_sz, caddr_t responce);
521 static int st_get_read_pos(struct scsi_tape *un, buf_t *bp);
522 static int st_logical_block_locate(struct scsi_tape *un, uint64_t lblk,
523     uchar_t partition);
524 static int st_mtfsf_ioctl(struct scsi_tape *un, int files);
525 static int st_mtfsr_ioctl(struct scsi_tape *un, int count);
526 static int st_mtbsf_ioctl(struct scsi_tape *un, int files);
527 static int st_mtnbsf_ioctl(struct scsi_tape *un, int count);
528 static int st_mtbsr_ioctl(struct scsi_tape *un, int num);
529 static int st_mtfsfm_ioctl(struct scsi_tape *un, int cnt);
530 static int st_mtbsfm_ioctl(struct scsi_tape *un, int cnt);
531 static int st_backward_space_files(struct scsi_tape *un, int count,
532     int infront);
533 static int st_forward_space_files(struct scsi_tape *un, int files);
534 static int st_scenic_route_to_begining_of_file(struct scsi_tape *un,
535     int32_t fileno);
536 static int st_space_to_begining_of_file(struct scsi_tape *un);
537 static int st_space_records(struct scsi_tape *un, int records);
538 
539 #if defined(__i386) || defined(__amd64)
540 /*
541  * routines for I/O in big block size
542  */
543 static void st_release_contig_mem(struct scsi_tape *un, struct contig_mem *cp);
544 static struct contig_mem *st_get_contig_mem(struct scsi_tape *un, size_t len,
545     int alloc_flags);
546 static int st_bigblk_xfer_done(struct buf *bp);
547 static struct buf *st_get_bigblk_bp(struct buf *bp);
548 #endif
549 static void st_print_position(struct scsi_tape *un, const char *comment,
550     tapepos_t *pos);
551 
552 /*
553  * error statistics create/update functions
554  */
555 static int st_create_errstats(struct scsi_tape *, int);
556 static int st_validate_tapemarks(struct scsi_tape *un, tapepos_t *pos);
557 
558 #ifdef STDEBUG
559 static void st_debug_cmds(struct scsi_tape *un, int com, int count, int wait);
560 static char *st_dev_name(dev_t dev);
561 #endif /* STDEBUG */
562 
563 #if !defined(lint)
564 _NOTE(SCHEME_PROTECTS_DATA("unique per pkt",
565     scsi_pkt buf uio scsi_cdb uscsi_cmd))
566 _NOTE(SCHEME_PROTECTS_DATA("unique per pkt", scsi_extended_sense scsi_status))
567 _NOTE(SCHEME_PROTECTS_DATA("stable data", scsi_device))
568 _NOTE(DATA_READABLE_WITHOUT_LOCK(st_drivetype scsi_address))
569 #endif
570 
571 /*
572  * autoconfiguration routines.
573  */
574 char _depends_on[] = "misc/scsi";
575 
576 static struct modldrv modldrv = {
577 	&mod_driverops,		/* Type of module. This one is a driver */
578 	"SCSI tape Driver %I%", /* Name of the module. */
579 	&st_ops			/* driver ops */
580 };
581 
582 static struct modlinkage modlinkage = {
583 	MODREV_1, &modldrv, NULL
584 };
585 
586 /*
587  * Notes on Post Reset Behavior in the tape driver:
588  *
589  * When the tape drive is opened, the driver  attempts  to make sure that
590  * the tape head is positioned exactly where it was left when it was last
591  * closed  provided  the  medium  is not  changed.  If the tape  drive is
592  * opened in O_NDELAY mode, the repositioning  (if necessary for any loss
593  * of position due to reset) will happen when the first tape operation or
594  * I/O occurs.  The repositioning (if required) may not be possible under
595  * certain situations such as when the device firmware not able to report
596  * the medium  change in the REQUEST  SENSE data  because of a reset or a
597  * misbehaving  bus  not  allowing  the  reposition  to  happen.  In such
598  * extraordinary  situations, where the driver fails to position the head
599  * at its  original  position,  it will fail the open the first  time, to
600  * save the applications from overwriting the data.  All further attempts
601  * to open the tape device will result in the driver  attempting  to load
602  * the  tape at BOT  (beginning  of  tape).  Also a  warning  message  to
603  * indicate  that further  attempts to open the tape device may result in
604  * the tape being  loaded at BOT will be printed on the  console.  If the
605  * tape  device is opened  in  O_NDELAY  mode,  failure  to  restore  the
606  * original tape head  position,  will result in the failure of the first
607  * tape  operation  or I/O,  Further,  the  driver  will  invalidate  its
608  * internal tape position  which will  necessitate  the  applications  to
609  * validate the position by using either a tape  positioning  ioctl (such
610  * as MTREW) or closing and reopening the tape device.
611  *
612  */
613 
614 int
615 _init(void)
616 {
617 	int	e;
618 
619 	if (((e = ddi_soft_state_init(&st_state,
620 	    sizeof (struct scsi_tape), ST_MAXUNIT)) != 0)) {
621 		return (e);
622 	}
623 
624 	if ((e = mod_install(&modlinkage)) != 0) {
625 		ddi_soft_state_fini(&st_state);
626 	}
627 
628 #if defined(__x86)
629 	/* set the max physical address for iob allocs on x86 */
630 	st_alloc_attr.dma_attr_addr_hi = st_max_phys_addr;
631 
632 	/*
633 	 * set the sgllen for iob allocs on x86. If this is set less than
634 	 * the number of pages the buffer will take (taking into account
635 	 * alignment), it would force the allocator to try and allocate
636 	 * contiguous pages.
637 	 */
638 	st_alloc_attr.dma_attr_sgllen = st_sgl_size;
639 #endif
640 
641 	return (e);
642 }
643 
644 int
645 _fini(void)
646 {
647 	int e;
648 
649 	if ((e = mod_remove(&modlinkage)) != 0) {
650 		return (e);
651 	}
652 
653 	ddi_soft_state_fini(&st_state);
654 
655 	return (e);
656 }
657 
658 int
659 _info(struct modinfo *modinfop)
660 {
661 	return (mod_info(&modlinkage, modinfop));
662 }
663 
664 
665 static int
666 st_probe(dev_info_t *devi)
667 {
668 	int instance;
669 	struct scsi_device *devp;
670 	int rval;
671 
672 #if !defined(__sparc)
673 	char    *tape_prop;
674 	int	tape_prop_len;
675 #endif
676 
677 	ST_ENTR(devi, st_probe);
678 
679 	/* If self identifying device */
680 	if (ddi_dev_is_sid(devi) == DDI_SUCCESS) {
681 		return (DDI_PROBE_DONTCARE);
682 	}
683 
684 #if !defined(__sparc)
685 	/*
686 	 * Since some x86 HBAs have devnodes that look like SCSI as
687 	 * far as we can tell but aren't really SCSI (DADK, like mlx)
688 	 * we check for the presence of the "tape" property.
689 	 */
690 	if (ddi_prop_op(DDI_DEV_T_NONE, devi, PROP_LEN_AND_VAL_ALLOC,
691 	    DDI_PROP_CANSLEEP, "tape",
692 	    (caddr_t)&tape_prop, &tape_prop_len) != DDI_PROP_SUCCESS) {
693 		return (DDI_PROBE_FAILURE);
694 	}
695 	if (strncmp(tape_prop, "sctp", tape_prop_len) != 0) {
696 		kmem_free(tape_prop, tape_prop_len);
697 		return (DDI_PROBE_FAILURE);
698 	}
699 	kmem_free(tape_prop, tape_prop_len);
700 #endif
701 
702 	devp = ddi_get_driver_private(devi);
703 	instance = ddi_get_instance(devi);
704 
705 	if (ddi_get_soft_state(st_state, instance) != NULL) {
706 		return (DDI_PROBE_PARTIAL);
707 	}
708 
709 
710 	/*
711 	 * Turn around and call probe routine to see whether
712 	 * we actually have a tape at this SCSI nexus.
713 	 */
714 	if (scsi_probe(devp, NULL_FUNC) == SCSIPROBE_EXISTS) {
715 
716 		/*
717 		 * In checking the whole inq_dtype byte we are looking at both
718 		 * the Peripheral Qualifier and the Peripheral Device Type.
719 		 * For this driver we are only interested in sequential devices
720 		 * that are connected or capable if connecting to this logical
721 		 * unit.
722 		 */
723 		if (devp->sd_inq->inq_dtype ==
724 		    (DTYPE_SEQUENTIAL | DPQ_POSSIBLE)) {
725 			ST_DEBUG6(devi, st_label, SCSI_DEBUG,
726 			    "probe exists\n");
727 			rval = DDI_PROBE_SUCCESS;
728 		} else {
729 			rval = DDI_PROBE_FAILURE;
730 		}
731 	} else {
732 		ST_DEBUG6(devi, st_label, SCSI_DEBUG,
733 		    "probe failure: nothing there\n");
734 		rval = DDI_PROBE_FAILURE;
735 	}
736 	scsi_unprobe(devp);
737 	return (rval);
738 }
739 
740 static int
741 st_attach(dev_info_t *devi, ddi_attach_cmd_t cmd)
742 {
743 	int 	instance;
744 	int	wide;
745 	int 	dev_instance;
746 	int	ret_status;
747 	struct	scsi_device *devp;
748 	int	node_ix;
749 	struct	scsi_tape *un;
750 
751 	ST_ENTR(devi, st_attach);
752 
753 	devp = ddi_get_driver_private(devi);
754 	instance = ddi_get_instance(devi);
755 
756 	switch (cmd) {
757 		case DDI_ATTACH:
758 			if (st_doattach(devp, SLEEP_FUNC) == DDI_FAILURE) {
759 				return (DDI_FAILURE);
760 			}
761 			break;
762 		case DDI_RESUME:
763 			/*
764 			 * Suspend/Resume
765 			 *
766 			 * When the driver suspended, there might be
767 			 * outstanding cmds and therefore we need to
768 			 * reset the suspended flag and resume the scsi
769 			 * watch thread and restart commands and timeouts
770 			 */
771 
772 			if (!(un = ddi_get_soft_state(st_state, instance))) {
773 				return (DDI_FAILURE);
774 			}
775 			dev_instance = ((un->un_dev == 0) ? MTMINOR(instance) :
776 			    un->un_dev);
777 
778 			mutex_enter(ST_MUTEX);
779 
780 			un->un_throttle = un->un_max_throttle;
781 			un->un_tids_at_suspend = 0;
782 			un->un_pwr_mgmt = ST_PWR_NORMAL;
783 
784 			if (un->un_swr_token) {
785 				scsi_watch_resume(un->un_swr_token);
786 			}
787 
788 			/*
789 			 * Restart timeouts
790 			 */
791 			if ((un->un_tids_at_suspend & ST_DELAY_TID) != 0) {
792 				mutex_exit(ST_MUTEX);
793 				un->un_delay_tid = timeout(
794 				    st_delayed_cv_broadcast, un,
795 				    drv_usectohz((clock_t)
796 				    MEDIA_ACCESS_DELAY));
797 				mutex_enter(ST_MUTEX);
798 			}
799 
800 			if (un->un_tids_at_suspend & ST_HIB_TID) {
801 				mutex_exit(ST_MUTEX);
802 				un->un_hib_tid = timeout(st_intr_restart, un,
803 				    ST_STATUS_BUSY_TIMEOUT);
804 				mutex_enter(ST_MUTEX);
805 			}
806 
807 			ret_status = st_clear_unit_attentions(dev_instance, 5);
808 
809 			/*
810 			 * now check if we need to restore the tape position
811 			 */
812 			if ((un->un_suspend_pos.pmode != invalid) &&
813 			    ((un->un_suspend_pos.fileno > 0) ||
814 			    (un->un_suspend_pos.blkno > 0)) ||
815 			    (un->un_suspend_pos.lgclblkno > 0)) {
816 				if (ret_status != 0) {
817 					/*
818 					 * tape didn't get good TUR
819 					 * just print out error messages
820 					 */
821 					scsi_log(ST_DEVINFO, st_label, CE_WARN,
822 					    "st_attach-RESUME: tape failure "
823 					    " tape position will be lost");
824 				} else {
825 					/* this prints errors */
826 					(void) st_validate_tapemarks(un,
827 					    &un->un_suspend_pos);
828 				}
829 				/*
830 				 * there are no retries, if there is an error
831 				 * we don't know if the tape has changed
832 				 */
833 				un->un_suspend_pos.pmode = invalid;
834 			}
835 
836 			/* now we are ready to start up any queued I/Os */
837 			if (un->un_ncmds || un->un_quef) {
838 				st_start(un);
839 			}
840 
841 			cv_broadcast(&un->un_suspend_cv);
842 			mutex_exit(ST_MUTEX);
843 			return (DDI_SUCCESS);
844 
845 		default:
846 			return (DDI_FAILURE);
847 	}
848 
849 	un = ddi_get_soft_state(st_state, instance);
850 
851 	ST_DEBUG(devi, st_label, SCSI_DEBUG,
852 	    "st_attach: instance=%x\n", instance);
853 
854 	/*
855 	 * find the drive type for this target
856 	 */
857 	st_known_tape_type(un);
858 
859 	for (node_ix = 0; node_ix < ST_NUM_MEMBERS(st_minor_data); node_ix++) {
860 		int minor;
861 		char *name;
862 
863 		name  = st_minor_data[node_ix].name;
864 		minor = st_minor_data[node_ix].minor;
865 
866 		/*
867 		 * For default devices set the density to the
868 		 * preferred default density for this device.
869 		 */
870 		if (node_ix <= DEF_BSD_NR) {
871 			minor |= un->un_dp->default_density;
872 		}
873 		minor |= MTMINOR(instance);
874 
875 		if (ddi_create_minor_node(devi, name, S_IFCHR, minor,
876 		    DDI_NT_TAPE, NULL) == DDI_SUCCESS) {
877 			continue;
878 		}
879 
880 		ddi_remove_minor_node(devi, NULL);
881 		if (un) {
882 			cv_destroy(&un->un_clscv);
883 			cv_destroy(&un->un_sbuf_cv);
884 			cv_destroy(&un->un_queue_cv);
885 			cv_destroy(&un->un_state_cv);
886 			cv_destroy(&un->un_suspend_cv);
887 			cv_destroy(&un->un_tape_busy_cv);
888 
889 			if (un->un_sbufp) {
890 				freerbuf(un->un_sbufp);
891 			}
892 			if (un->un_uscsi_rqs_buf) {
893 				kmem_free(un->un_uscsi_rqs_buf, SENSE_LENGTH);
894 			}
895 			if (un->un_mspl) {
896 				i_ddi_mem_free((caddr_t)un->un_mspl, NULL);
897 			}
898 			scsi_destroy_pkt(un->un_rqs);
899 			scsi_free_consistent_buf(un->un_rqs_bp);
900 			ddi_soft_state_free(st_state, instance);
901 			devp->sd_private = NULL;
902 			devp->sd_sense = NULL;
903 
904 		}
905 		ddi_prop_remove_all(devi);
906 		return (DDI_FAILURE);
907 	}
908 
909 	/*
910 	 * Add a zero-length attribute to tell the world we support
911 	 * kernel ioctls (for layered drivers)
912 	 */
913 	(void) ddi_prop_create(DDI_DEV_T_NONE, devi, DDI_PROP_CANSLEEP,
914 	    DDI_KERNEL_IOCTL, NULL, 0);
915 
916 	ddi_report_dev((dev_info_t *)devi);
917 
918 	/*
919 	 * If it's a SCSI-2 tape drive which supports wide,
920 	 * tell the host adapter to use wide.
921 	 */
922 	wide = ((devp->sd_inq->inq_rdf == RDF_SCSI2) &&
923 	    (devp->sd_inq->inq_wbus16 || devp->sd_inq->inq_wbus32)) ?  1 : 0;
924 
925 	if (scsi_ifsetcap(ROUTE, "wide-xfer", wide, 1) == 1) {
926 		ST_DEBUG(devi, st_label, SCSI_DEBUG,
927 		    "Wide Transfer %s\n", wide ? "enabled" : "disabled");
928 	}
929 
930 	/*
931 	 * enable autorequest sense; keep the rq packet around in case
932 	 * the autorequest sense fails because of a busy condition
933 	 * do a getcap first in case the capability is not variable
934 	 */
935 	if (scsi_ifgetcap(ROUTE, "auto-rqsense", 1) == 1) {
936 		un->un_arq_enabled = 1;
937 	} else {
938 		un->un_arq_enabled =
939 		    ((scsi_ifsetcap(ROUTE, "auto-rqsense", 1, 1) == 1) ? 1 : 0);
940 	}
941 
942 
943 	ST_DEBUG(devi, st_label, SCSI_DEBUG, "auto request sense %s\n",
944 	    (un->un_arq_enabled ? "enabled" : "disabled"));
945 
946 	un->un_untagged_qing =
947 	    (scsi_ifgetcap(ROUTE, "untagged-qing", 0) == 1);
948 
949 	/*
950 	 * XXX - This is just for 2.6.  to tell users that write buffering
951 	 *	has gone away.
952 	 */
953 	if (un->un_arq_enabled && un->un_untagged_qing) {
954 		if (ddi_getprop(DDI_DEV_T_ANY, devi, DDI_PROP_DONTPASS,
955 		    "tape-driver-buffering", 0) != 0) {
956 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
957 			    "Write Data Buffering has been depricated. Your "
958 			    "applications should continue to work normally.\n"
959 			    " But, they should  ported to use Asynchronous "
960 			    " I/O\n"
961 			    " For more information, read about "
962 			    " tape-driver-buffering "
963 			    "property in the st(7d) man page\n");
964 		}
965 	}
966 
967 	un->un_max_throttle = un->un_throttle = un->un_last_throttle = 1;
968 	un->un_flush_on_errors = 0;
969 	un->un_mkr_pkt = (struct scsi_pkt *)NULL;
970 
971 	ST_DEBUG(devi, st_label, SCSI_DEBUG,
972 	    "throttle=%x, max_throttle = %x\n",
973 	    un->un_throttle, un->un_max_throttle);
974 
975 	/* initialize persistent errors to nil */
976 	un->un_persistence = 0;
977 	un->un_persist_errors = 0;
978 
979 	/*
980 	 * Get dma-max from HBA driver. If it is not defined, use 64k
981 	 */
982 	un->un_maxdma	= scsi_ifgetcap(&devp->sd_address, "dma-max", 1);
983 	if (un->un_maxdma == -1) {
984 		ST_DEBUG(devi, st_label, SCSI_DEBUG,
985 		    "Received a value that looked like -1. Using 64k maxdma");
986 		un->un_maxdma = (64 * ONE_K);
987 	}
988 
989 	/*
990 	 * Get the max allowable cdb size
991 	 */
992 	un->un_max_cdb_sz =
993 	    scsi_ifgetcap(&devp->sd_address, "max-cdb-length", 1);
994 	if (un->un_max_cdb_sz < CDB_GROUP0) {
995 		ST_DEBUG(devi, st_label, SCSI_DEBUG,
996 		    "HBA reported max-cdb-length as %d\n", un->un_max_cdb_sz);
997 		un->un_max_cdb_sz = CDB_GROUP4; /* optimistic default */
998 	}
999 
1000 	un->un_maxbsize = MAXBSIZE_UNKNOWN;
1001 
1002 	un->un_mediastate = MTIO_NONE;
1003 	un->un_HeadClean  = TAPE_ALERT_SUPPORT_UNKNOWN;
1004 
1005 	/*
1006 	 * initialize kstats
1007 	 */
1008 	un->un_stats = kstat_create("st", instance, NULL, "tape",
1009 	    KSTAT_TYPE_IO, 1, KSTAT_FLAG_PERSISTENT);
1010 	if (un->un_stats) {
1011 		un->un_stats->ks_lock = ST_MUTEX;
1012 		kstat_install(un->un_stats);
1013 	}
1014 	(void) st_create_errstats(un, instance);
1015 
1016 	return (DDI_SUCCESS);
1017 }
1018 
1019 /*
1020  * st_detach:
1021  *
1022  * we allow a detach if and only if:
1023  *	- no tape is currently inserted
1024  *	- tape position is at BOT or unknown
1025  *		(if it is not at BOT then a no rewind
1026  *		device was opened and we have to preserve state)
1027  *	- it must be in a closed state : no timeouts or scsi_watch requests
1028  *		will exist if it is closed, so we don't need to check for
1029  *		them here.
1030  */
1031 /*ARGSUSED*/
1032 static int
1033 st_detach(dev_info_t *devi, ddi_detach_cmd_t cmd)
1034 {
1035 	int 	instance;
1036 	int 	dev_instance;
1037 	struct scsi_device *devp;
1038 	struct scsi_tape *un;
1039 	clock_t wait_cmds_complete;
1040 
1041 	ST_ENTR(devi, st_detach);
1042 
1043 	instance = ddi_get_instance(devi);
1044 
1045 	if (!(un = ddi_get_soft_state(st_state, instance))) {
1046 		return (DDI_FAILURE);
1047 	}
1048 
1049 	switch (cmd) {
1050 
1051 	case DDI_DETACH:
1052 		/*
1053 		 * Undo what we did in st_attach & st_doattach,
1054 		 * freeing resources and removing things we installed.
1055 		 * The system framework guarantees we are not active
1056 		 * with this devinfo node in any other entry points at
1057 		 * this time.
1058 		 */
1059 
1060 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1061 		    "st_detach: instance=%x, un=%p\n", instance,
1062 		    (void *)un);
1063 
1064 		if (((un->un_dp->options & ST_UNLOADABLE) == 0) ||
1065 		    (un->un_ncmds != 0) || (un->un_quef != NULL) ||
1066 		    (un->un_state != ST_STATE_CLOSED)) {
1067 			/*
1068 			 * we cannot unload some targets because the
1069 			 * inquiry returns junk unless immediately
1070 			 * after a reset
1071 			 */
1072 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
1073 			    "cannot unload instance %x\n", instance);
1074 			return (DDI_FAILURE);
1075 		}
1076 
1077 		/*
1078 		 * if the tape has been removed then we may unload;
1079 		 * do a test unit ready and if it returns NOT READY
1080 		 * then we assume that it is safe to unload.
1081 		 * as a side effect, pmode may be set to invalid if the
1082 		 * the test unit ready fails;
1083 		 * also un_state may be set to non-closed, so reset it
1084 		 */
1085 		if ((un->un_dev) &&		/* Been opened since attach */
1086 		    ((un->un_pos.pmode == legacy) &&
1087 		    (un->un_pos.fileno > 0) ||	/* Known position not rewound */
1088 		    (un->un_pos.blkno != 0)) ||	/* Or within first file */
1089 		    ((un->un_pos.pmode == logical) &&
1090 		    (un->un_pos.lgclblkno > 0))) {
1091 			mutex_enter(ST_MUTEX);
1092 			/*
1093 			 * Send Test Unit Ready in the hopes that if
1094 			 * the drive is not in the state we think it is.
1095 			 * And the state will be changed so it can be detached.
1096 			 * If the command fails to reach the device and
1097 			 * the drive was not rewound or unloaded we want
1098 			 * to fail the detach till a user command fails
1099 			 * where after the detach will succead.
1100 			 */
1101 			(void) st_cmd(un->un_dev, SCMD_TEST_UNIT_READY,
1102 			    0, SYNC_CMD);
1103 			/*
1104 			 * After TUR un_state may be set to non-closed,
1105 			 * so reset it back.
1106 			 */
1107 			un->un_state = ST_STATE_CLOSED;
1108 			mutex_exit(ST_MUTEX);
1109 		}
1110 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1111 		    "un_status=%x, fileno=%x, blkno=%x\n",
1112 		    un->un_status, un->un_pos.fileno, un->un_pos.blkno);
1113 
1114 		/*
1115 		 * check again:
1116 		 * if we are not at BOT then it is not safe to unload
1117 		 */
1118 		if ((un->un_dev) &&		/* Been opened since attach */
1119 		    (((un->un_pos.pmode == legacy) &&
1120 		    (un->un_pos.fileno > 0) ||	/* Known position not rewound */
1121 		    (un->un_pos.blkno != 0)) ||	/* Or within first file */
1122 		    ((un->un_pos.pmode == logical) &&
1123 		    (un->un_pos.lgclblkno > 0)))) {
1124 
1125 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1126 			    "cannot detach: pmode=%d fileno=%x, blkno=%x"
1127 			    " lgclblkno=0x%"PRIx64"\n", un->un_pos.pmode,
1128 			    un->un_pos.fileno, un->un_pos.blkno,
1129 			    un->un_pos.lgclblkno);
1130 			return (DDI_FAILURE);
1131 		}
1132 
1133 		/*
1134 		 * Just To make sure that we have released the
1135 		 * tape unit .
1136 		 */
1137 		if (un->un_dev && (un->un_rsvd_status & ST_RESERVE) &&
1138 		    !DEVI_IS_DEVICE_REMOVED(devi)) {
1139 			mutex_enter(ST_MUTEX);
1140 			(void) st_reserve_release(un, ST_RELEASE);
1141 			mutex_exit(ST_MUTEX);
1142 		}
1143 
1144 		/*
1145 		 * now remove other data structures allocated in st_doattach()
1146 		 */
1147 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1148 		    "destroying/freeing\n");
1149 		cv_destroy(&un->un_clscv);
1150 		cv_destroy(&un->un_sbuf_cv);
1151 		cv_destroy(&un->un_queue_cv);
1152 		cv_destroy(&un->un_suspend_cv);
1153 		cv_destroy(&un->un_tape_busy_cv);
1154 
1155 		if (un->un_hib_tid) {
1156 			(void) untimeout(un->un_hib_tid);
1157 			un->un_hib_tid = 0;
1158 		}
1159 
1160 		if (un->un_delay_tid) {
1161 			(void) untimeout(un->un_delay_tid);
1162 			un->un_delay_tid = 0;
1163 		}
1164 		cv_destroy(&un->un_state_cv);
1165 
1166 #if defined(__i386) || defined(__amd64)
1167 		if (un->un_contig_mem_hdl != NULL) {
1168 			ddi_dma_free_handle(&un->un_contig_mem_hdl);
1169 		}
1170 #endif
1171 		if (un->un_sbufp) {
1172 			freerbuf(un->un_sbufp);
1173 		}
1174 		if (un->un_uscsi_rqs_buf) {
1175 			kmem_free(un->un_uscsi_rqs_buf, SENSE_LENGTH);
1176 		}
1177 		if (un->un_mspl) {
1178 			i_ddi_mem_free((caddr_t)un->un_mspl, NULL);
1179 		}
1180 		if (un->un_rqs) {
1181 			scsi_destroy_pkt(un->un_rqs);
1182 			scsi_free_consistent_buf(un->un_rqs_bp);
1183 		}
1184 		if (un->un_mkr_pkt) {
1185 			scsi_destroy_pkt(un->un_mkr_pkt);
1186 		}
1187 		if (un->un_arq_enabled) {
1188 			(void) scsi_ifsetcap(ROUTE, "auto-rqsense", 0, 1);
1189 		}
1190 		if (un->un_dp_size) {
1191 			kmem_free(un->un_dp, un->un_dp_size);
1192 		}
1193 		if (un->un_stats) {
1194 			kstat_delete(un->un_stats);
1195 			un->un_stats = (kstat_t *)0;
1196 		}
1197 		if (un->un_errstats) {
1198 			kstat_delete(un->un_errstats);
1199 			un->un_errstats = (kstat_t *)0;
1200 		}
1201 		devp = ST_SCSI_DEVP;
1202 		ddi_soft_state_free(st_state, instance);
1203 		devp->sd_private = NULL;
1204 		devp->sd_sense = NULL;
1205 		scsi_unprobe(devp);
1206 		ddi_prop_remove_all(devi);
1207 		ddi_remove_minor_node(devi, NULL);
1208 		ST_DEBUG(0, st_label, SCSI_DEBUG, "st_detach done\n");
1209 		return (DDI_SUCCESS);
1210 
1211 	case DDI_SUSPEND:
1212 
1213 		/*
1214 		 * Suspend/Resume
1215 		 *
1216 		 * To process DDI_SUSPEND, we must do the following:
1217 		 *
1218 		 *  - check ddi_removing_power to see if power will be turned
1219 		 *    off. if so, return DDI_FAILURE
1220 		 *  - check if we are already suspended,
1221 		 *    if so, return DDI_FAILURE
1222 		 *  - check if device state is CLOSED,
1223 		 *    if not, return DDI_FAILURE.
1224 		 *  - wait until outstanding operations complete
1225 		 *  - save tape state
1226 		 *  - block new operations
1227 		 *  - cancel pending timeouts
1228 		 *
1229 		 */
1230 
1231 		if (ddi_removing_power(devi)) {
1232 			return (DDI_FAILURE);
1233 		}
1234 		mutex_enter(ST_MUTEX);
1235 
1236 		/*
1237 		 * Shouldn't already be suspended, if so return failure
1238 		 */
1239 		if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
1240 			mutex_exit(ST_MUTEX);
1241 			return (DDI_FAILURE);
1242 		}
1243 		if (un->un_state != ST_STATE_CLOSED) {
1244 			mutex_exit(ST_MUTEX);
1245 			return (DDI_FAILURE);
1246 		}
1247 
1248 		/*
1249 		 * Wait for all outstanding I/O's to complete
1250 		 *
1251 		 * we wait on both ncmds and the wait queue for times
1252 		 * when we are flushing after persistent errors are
1253 		 * flagged, which is when ncmds can be 0, and the
1254 		 * queue can still have I/O's.  This way we preserve
1255 		 * order of biodone's.
1256 		 */
1257 		wait_cmds_complete = ddi_get_lbolt();
1258 		wait_cmds_complete +=
1259 		    st_wait_cmds_complete * drv_usectohz(1000000);
1260 		while (un->un_ncmds || un->un_quef ||
1261 		    (un->un_state == ST_STATE_RESOURCE_WAIT)) {
1262 
1263 			if (cv_timedwait(&un->un_tape_busy_cv, ST_MUTEX,
1264 			    wait_cmds_complete) == -1) {
1265 				/*
1266 				 * Time expired then cancel the command
1267 				 */
1268 				mutex_exit(ST_MUTEX);
1269 				if (scsi_reset(ROUTE, RESET_TARGET) == 0) {
1270 					mutex_enter(ST_MUTEX);
1271 					if (un->un_last_throttle) {
1272 						un->un_throttle =
1273 						    un->un_last_throttle;
1274 					}
1275 					mutex_exit(ST_MUTEX);
1276 					return (DDI_FAILURE);
1277 				} else {
1278 					mutex_enter(ST_MUTEX);
1279 					break;
1280 				}
1281 			}
1282 		}
1283 
1284 		/*
1285 		 * DDI_SUSPEND says that the system "may" power down, we
1286 		 * remember the file and block number before rewinding.
1287 		 * we also need to save state before issuing
1288 		 * any WRITE_FILE_MARK command.
1289 		 */
1290 		(void) st_update_block_pos(un);
1291 		COPY_POS(&un->un_suspend_pos, &un->un_pos);
1292 
1293 		dev_instance = ((un->un_dev == 0) ? MTMINOR(instance) :
1294 		    un->un_dev);
1295 
1296 		/*
1297 		 * Issue a zero write file fmk command to tell the drive to
1298 		 * flush any buffered tape marks
1299 		 */
1300 		(void) st_cmd(dev_instance, SCMD_WRITE_FILE_MARK, 0, SYNC_CMD);
1301 
1302 		/*
1303 		 * Because not all tape drives correctly implement buffer
1304 		 * flushing with the zero write file fmk command, issue a
1305 		 * synchronous rewind command to force data flushing.
1306 		 * st_validate_tapemarks() will do a rewind during DDI_RESUME
1307 		 * anyway.
1308 		 */
1309 		(void) st_cmd(dev_instance, SCMD_REWIND, 0, SYNC_CMD);
1310 
1311 		/* stop any new operations */
1312 		un->un_pwr_mgmt = ST_PWR_SUSPENDED;
1313 		un->un_throttle = 0;
1314 
1315 		/*
1316 		 * cancel any outstanding timeouts
1317 		 */
1318 		if (un->un_delay_tid) {
1319 			timeout_id_t temp_id = un->un_delay_tid;
1320 			un->un_delay_tid = 0;
1321 			un->un_tids_at_suspend |= ST_DELAY_TID;
1322 			mutex_exit(ST_MUTEX);
1323 			(void) untimeout(temp_id);
1324 			mutex_enter(ST_MUTEX);
1325 		}
1326 
1327 		if (un->un_hib_tid) {
1328 			timeout_id_t temp_id = un->un_hib_tid;
1329 			un->un_hib_tid = 0;
1330 			un->un_tids_at_suspend |= ST_HIB_TID;
1331 			mutex_exit(ST_MUTEX);
1332 			(void) untimeout(temp_id);
1333 			mutex_enter(ST_MUTEX);
1334 		}
1335 
1336 		/*
1337 		 * Suspend the scsi_watch_thread
1338 		 */
1339 		if (un->un_swr_token) {
1340 			opaque_t temp_token = un->un_swr_token;
1341 			mutex_exit(ST_MUTEX);
1342 			scsi_watch_suspend(temp_token);
1343 		} else {
1344 			mutex_exit(ST_MUTEX);
1345 		}
1346 
1347 		return (DDI_SUCCESS);
1348 
1349 	default:
1350 		ST_DEBUG(0, st_label, SCSI_DEBUG, "st_detach failed\n");
1351 		return (DDI_FAILURE);
1352 	}
1353 }
1354 
1355 
1356 /* ARGSUSED */
1357 static int
1358 stinfo(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
1359 {
1360 	dev_t dev;
1361 	struct scsi_tape *un;
1362 	int instance, error;
1363 
1364 	ST_ENTR(dip, stinfo);
1365 
1366 	switch (infocmd) {
1367 	case DDI_INFO_DEVT2DEVINFO:
1368 		dev = (dev_t)arg;
1369 		instance = MTUNIT(dev);
1370 		if ((un = ddi_get_soft_state(st_state, instance)) == NULL)
1371 			return (DDI_FAILURE);
1372 		*result = (void *) ST_DEVINFO;
1373 		error = DDI_SUCCESS;
1374 		break;
1375 	case DDI_INFO_DEVT2INSTANCE:
1376 		dev = (dev_t)arg;
1377 		instance = MTUNIT(dev);
1378 		*result = (void *)(uintptr_t)instance;
1379 		error = DDI_SUCCESS;
1380 		break;
1381 	default:
1382 		error = DDI_FAILURE;
1383 	}
1384 	return (error);
1385 }
1386 
1387 static int
1388 st_doattach(struct scsi_device *devp, int (*canwait)())
1389 {
1390 	struct scsi_pkt *rqpkt = NULL;
1391 	struct scsi_tape *un = NULL;
1392 	int km_flags = (canwait != NULL_FUNC) ? KM_SLEEP : KM_NOSLEEP;
1393 	int instance;
1394 	struct buf *bp;
1395 	size_t rlen;
1396 
1397 	ST_FUNC(devp->sd_dev, st_doattach);
1398 	/*
1399 	 * Call the routine scsi_probe to do some of the dirty work.
1400 	 * If the INQUIRY command succeeds, the field sd_inq in the
1401 	 * device structure will be filled in.
1402 	 */
1403 	ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1404 	    "st_doattach(): probing\n");
1405 
1406 	if (scsi_probe(devp, canwait) == SCSIPROBE_EXISTS) {
1407 
1408 		/*
1409 		 * In checking the whole inq_dtype byte we are looking at both
1410 		 * the Peripheral Qualifier and the Peripheral Device Type.
1411 		 * For this driver we are only interested in sequential devices
1412 		 * that are connected or capable if connecting to this logical
1413 		 * unit.
1414 		 */
1415 		if (devp->sd_inq->inq_dtype ==
1416 		    (DTYPE_SEQUENTIAL | DPQ_POSSIBLE)) {
1417 			ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1418 			    "probe exists\n");
1419 		} else {
1420 			/* Something there but not a tape device */
1421 			scsi_unprobe(devp);
1422 			return (DDI_FAILURE);
1423 		}
1424 	} else {
1425 		/* Nothing there */
1426 		ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1427 		    "probe failure: nothing there\n");
1428 		scsi_unprobe(devp);
1429 		return (DDI_FAILURE);
1430 	}
1431 
1432 	bp = scsi_alloc_consistent_buf(&devp->sd_address, (struct buf *)NULL,
1433 	    SENSE_LENGTH, B_READ, canwait, NULL);
1434 	if (!bp) {
1435 		goto error;
1436 	}
1437 	rqpkt = scsi_init_pkt(&devp->sd_address, NULL, bp, CDB_GROUP0, 1, 0,
1438 	    PKT_CONSISTENT, canwait, NULL);
1439 	if (!rqpkt) {
1440 		goto error;
1441 	}
1442 	devp->sd_sense = (struct scsi_extended_sense *)bp->b_un.b_addr;
1443 	ASSERT(geterror(bp) == NULL);
1444 
1445 	(void) scsi_setup_cdb((union scsi_cdb *)rqpkt->pkt_cdbp,
1446 	    SCMD_REQUEST_SENSE, 0, SENSE_LENGTH, 0);
1447 	FILL_SCSI1_LUN(devp, rqpkt);
1448 
1449 	/*
1450 	 * The actual unit is present.
1451 	 * Now is the time to fill in the rest of our info..
1452 	 */
1453 	instance = ddi_get_instance(devp->sd_dev);
1454 
1455 	if (ddi_soft_state_zalloc(st_state, instance) != DDI_SUCCESS) {
1456 		goto error;
1457 	}
1458 	un = ddi_get_soft_state(st_state, instance);
1459 
1460 	ASSERT(un != NULL);
1461 
1462 	un->un_sbufp = getrbuf(km_flags);
1463 
1464 	un->un_uscsi_rqs_buf = kmem_alloc(SENSE_LENGTH, KM_SLEEP);
1465 
1466 	/*
1467 	 * use i_ddi_mem_alloc() for now until we have an interface to allocate
1468 	 * memory for DMA which doesn't require a DMA handle. ddi_iopb_alloc()
1469 	 * is obsolete and we want more flexibility in controlling the DMA
1470 	 * address constraints.
1471 	 */
1472 	(void) i_ddi_mem_alloc(devp->sd_dev, &st_alloc_attr,
1473 	    sizeof (struct seq_mode), ((km_flags == KM_SLEEP) ? 1 : 0), 0,
1474 	    NULL, (caddr_t *)&un->un_mspl, &rlen, NULL);
1475 
1476 	(void) i_ddi_mem_alloc(devp->sd_dev, &st_alloc_attr,
1477 	    sizeof (read_pos_data_t), ((km_flags == KM_SLEEP) ? 1 : 0), 0,
1478 	    NULL, (caddr_t *)&un->un_read_pos_data, &rlen, NULL);
1479 
1480 	if (!un->un_sbufp || !un->un_mspl || !un->un_read_pos_data) {
1481 		ST_DEBUG6(devp->sd_dev, st_label, SCSI_DEBUG,
1482 		    "probe partial failure: no space\n");
1483 		goto error;
1484 	}
1485 
1486 	bzero(un->un_mspl, sizeof (struct seq_mode));
1487 
1488 	cv_init(&un->un_sbuf_cv, NULL, CV_DRIVER, NULL);
1489 	cv_init(&un->un_queue_cv, NULL, CV_DRIVER, NULL);
1490 	cv_init(&un->un_clscv, NULL, CV_DRIVER, NULL);
1491 	cv_init(&un->un_state_cv, NULL, CV_DRIVER, NULL);
1492 #if defined(__i386) || defined(__amd64)
1493 	cv_init(&un->un_contig_mem_cv, NULL, CV_DRIVER, NULL);
1494 #endif
1495 
1496 	/* Initialize power managemnet condition variable */
1497 	cv_init(&un->un_suspend_cv, NULL, CV_DRIVER, NULL);
1498 	cv_init(&un->un_tape_busy_cv, NULL, CV_DRIVER, NULL);
1499 
1500 	rqpkt->pkt_flags |= (FLAG_SENSING | FLAG_HEAD | FLAG_NODISCON);
1501 
1502 	un->un_pos.pmode = invalid;
1503 	rqpkt->pkt_time = st_io_time;
1504 	rqpkt->pkt_comp = st_intr;
1505 	un->un_rqs	= rqpkt;
1506 	un->un_sd	= devp;
1507 	un->un_rqs_bp	= bp;
1508 	un->un_swr_token = (opaque_t)NULL;
1509 	un->un_comp_page = ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE;
1510 	un->un_wormable = st_is_drive_worm;
1511 	un->un_read_pos_type = LONG_POS;
1512 
1513 	un->un_suspend_pos.pmode = invalid;
1514 
1515 #if defined(__i386) || defined(__amd64)
1516 	if (ddi_dma_alloc_handle(ST_DEVINFO, &st_contig_mem_dma_attr,
1517 	    DDI_DMA_SLEEP, NULL, &un->un_contig_mem_hdl) != DDI_SUCCESS) {
1518 		ST_DEBUG6(devp->sd_dev, st_label, SCSI_DEBUG,
1519 		    "allocation of contiguous memory dma handle failed!");
1520 		un->un_contig_mem_hdl = NULL;
1521 		goto error;
1522 	}
1523 #endif
1524 
1525 	/*
1526 	 * Since this driver manages devices with "remote" hardware,
1527 	 * i.e. the devices themselves have no "reg" properties,
1528 	 * the SUSPEND/RESUME commands in detach/attach will not be
1529 	 * called by the power management framework unless we request
1530 	 * it by creating a "pm-hardware-state" property and setting it
1531 	 * to value "needs-suspend-resume".
1532 	 */
1533 	if (ddi_prop_update_string(DDI_DEV_T_NONE, devp->sd_dev,
1534 	    "pm-hardware-state", "needs-suspend-resume") !=
1535 	    DDI_PROP_SUCCESS) {
1536 
1537 		ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1538 		    "ddi_prop_update(\"pm-hardware-state\") failed\n");
1539 		goto error;
1540 	}
1541 
1542 	if (ddi_prop_create(DDI_DEV_T_NONE, devp->sd_dev, DDI_PROP_CANSLEEP,
1543 	    "no-involuntary-power-cycles", NULL, 0) != DDI_PROP_SUCCESS) {
1544 
1545 		ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1546 		    "ddi_prop_create(\"no-involuntary-power-cycles\") "
1547 		    "failed\n");
1548 		goto error;
1549 	}
1550 
1551 	ST_DEBUG6(devp->sd_dev, st_label, SCSI_DEBUG, "probe success\n");
1552 	return (DDI_SUCCESS);
1553 
1554 error:
1555 	devp->sd_sense = NULL;
1556 
1557 	ddi_remove_minor_node(devp->sd_dev, NULL);
1558 	if (un) {
1559 		if (un->un_mspl) {
1560 			i_ddi_mem_free((caddr_t)un->un_mspl, NULL);
1561 		}
1562 		if (un->un_read_pos_data) {
1563 			i_ddi_mem_free((caddr_t)un->un_read_pos_data, 0);
1564 		}
1565 		if (un->un_sbufp) {
1566 			freerbuf(un->un_sbufp);
1567 		}
1568 		if (un->un_uscsi_rqs_buf) {
1569 			kmem_free(un->un_uscsi_rqs_buf, SENSE_LENGTH);
1570 		}
1571 #if defined(__i386) || defined(__amd64)
1572 		if (un->un_contig_mem_hdl != NULL) {
1573 			ddi_dma_free_handle(&un->un_contig_mem_hdl);
1574 		}
1575 #endif
1576 		ddi_soft_state_free(st_state, instance);
1577 		devp->sd_private = NULL;
1578 	}
1579 
1580 	if (rqpkt) {
1581 		scsi_destroy_pkt(rqpkt);
1582 	}
1583 
1584 	if (bp) {
1585 		scsi_free_consistent_buf(bp);
1586 	}
1587 
1588 	if (devp->sd_inq) {
1589 		scsi_unprobe(devp);
1590 	}
1591 	return (DDI_FAILURE);
1592 }
1593 
1594 typedef int
1595 (*cfg_functp)(struct scsi_tape *, char *vidpid, struct st_drivetype *);
1596 
1597 static cfg_functp config_functs[] = {
1598 	st_get_conf_from_st_dot_conf,
1599 	st_get_conf_from_st_conf_dot_c,
1600 	st_get_default_conf
1601 };
1602 
1603 
1604 /*
1605  * determine tape type, using tape-config-list or built-in table or
1606  * use a generic tape config entry
1607  */
1608 static void
1609 st_known_tape_type(struct scsi_tape *un)
1610 {
1611 	struct st_drivetype *dp;
1612 	cfg_functp *config_funct;
1613 
1614 	ST_FUNC(ST_DEVINFO, st_known_tape_type);
1615 	/*
1616 	 * XXX:  Emulex MT-02 (and emulators) predates SCSI-1 and has
1617 	 *	 no vid & pid inquiry data.  So, we provide one.
1618 	 */
1619 	if (ST_INQUIRY->inq_len == 0 ||
1620 	    (bcmp("\0\0\0\0\0\0\0\0", ST_INQUIRY->inq_vid, 8) == 0)) {
1621 		(void) strcpy((char *)ST_INQUIRY->inq_vid, ST_MT02_NAME);
1622 	}
1623 
1624 	un->un_dp_size = sizeof (struct st_drivetype);
1625 	dp = kmem_zalloc((size_t)un->un_dp_size, KM_SLEEP);
1626 	un->un_dp = dp;
1627 
1628 	/*
1629 	 * Loop through the configuration methods till one works.
1630 	 */
1631 	for (config_funct = &config_functs[0]; ; config_funct++) {
1632 		if ((*config_funct)(un, ST_INQUIRY->inq_vid, dp)) {
1633 			break;
1634 		}
1635 	}
1636 
1637 	/*
1638 	 * If we didn't just make up this configuration and
1639 	 * all the density codes are the same..
1640 	 * Set Auto Density over ride.
1641 	 */
1642 	if (*config_funct != st_get_default_conf) {
1643 		/*
1644 		 * If this device is one that is configured and all
1645 		 * densities are the same, This saves doing gets and set
1646 		 * that yield nothing.
1647 		 */
1648 		if ((dp->densities[0]) == (dp->densities[1]) &&
1649 		    (dp->densities[0]) == (dp->densities[2]) &&
1650 		    (dp->densities[0]) == (dp->densities[3])) {
1651 
1652 			dp->options |= ST_AUTODEN_OVERRIDE;
1653 		}
1654 	}
1655 
1656 
1657 	/*
1658 	 * Store tape drive characteristics.
1659 	 */
1660 	un->un_status = 0;
1661 	un->un_attached = 1;
1662 	un->un_init_options = dp->options;
1663 
1664 	/* setup operation time-outs based on options */
1665 	st_calculate_timeouts(un);
1666 
1667 	/* make sure if we are supposed to be variable, make it variable */
1668 	if (dp->options & ST_VARIABLE) {
1669 		dp->bsize = 0;
1670 	}
1671 
1672 	scsi_log(ST_DEVINFO, st_label, CE_NOTE, "?<%s>\n", dp->name);
1673 }
1674 
1675 
1676 typedef struct {
1677 	int mask;
1678 	int bottom;
1679 	int top;
1680 	char *name;
1681 } conf_limit;
1682 
1683 static const conf_limit conf_limits[] = {
1684 
1685 	-1,		1,		2,		"conf version",
1686 	-1,		MT_ISTS,	ST_LAST_TYPE,	"drive type",
1687 	-1,		0,		0xffffff,	"block size",
1688 	ST_VALID_OPTS,	0,		ST_VALID_OPTS,	"options",
1689 	-1,		0,		4,		"number of densities",
1690 	-1,		0,		UINT8_MAX,	"density code",
1691 	-1,		0,		3,		"default density",
1692 	-1,		0,		UINT16_MAX,	"non motion timeout",
1693 	-1,		0,		UINT16_MAX,	"I/O timeout",
1694 	-1,		0,		UINT16_MAX,	"space timeout",
1695 	-1,		0,		UINT16_MAX,	"load timeout",
1696 	-1,		0,		UINT16_MAX,	"unload timeout",
1697 	-1,		0,		UINT16_MAX,	"erase timeout",
1698 	0,		0,		0,		NULL
1699 };
1700 
1701 static int
1702 st_validate_conf_data(struct scsi_tape *un, int *list, int list_len,
1703     const char *conf_name)
1704 {
1705 	int dens;
1706 	int ndens;
1707 	int value;
1708 	int type;
1709 	int count;
1710 	const conf_limit *limit = &conf_limits[0];
1711 
1712 	ST_FUNC(ST_DEVINFO, st_validate_conf_data);
1713 
1714 	ST_DEBUG3(ST_DEVINFO, st_label, CE_NOTE,
1715 	    "Checking %d entrys total with %d densities\n", list_len, list[4]);
1716 
1717 	count = list_len;
1718 	type = *list;
1719 	for (;  count && limit->name; count--, list++, limit++) {
1720 
1721 		value = *list;
1722 		if (value & ~limit->mask) {
1723 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1724 			    "%s %s value invalid bits set: 0x%X\n",
1725 			    conf_name, limit->name, value & ~limit->mask);
1726 			*list &= limit->mask;
1727 		} else if (value < limit->bottom) {
1728 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1729 			    "%s %s value too low: value = %d limit %d\n",
1730 			    conf_name, limit->name, value, limit->bottom);
1731 		} else if (value > limit->top) {
1732 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1733 			    "%s %s value too high: value = %d limit %d\n",
1734 			    conf_name, limit->name, value, limit->top);
1735 		} else {
1736 			ST_DEBUG3(ST_DEVINFO, st_label, CE_CONT,
1737 			    "%s %s value = 0x%X\n",
1738 			    conf_name, limit->name, value);
1739 		}
1740 
1741 		/* If not the number of densities continue */
1742 		if (limit != &conf_limits[4]) {
1743 			continue;
1744 		}
1745 
1746 		/* If number of densities is not in range can't use config */
1747 		if (value < limit->bottom || value > limit->top) {
1748 			return (-1);
1749 		}
1750 
1751 		ndens = min(value, NDENSITIES);
1752 		if ((type == 1) && (list_len - ndens) != 6) {
1753 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1754 			    "%s conf version 1 with %d densities has %d items"
1755 			    " should have %d",
1756 			    conf_name, ndens, list_len, 6 + ndens);
1757 		} else if ((type == 2) && (list_len - ndens) != 13) {
1758 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1759 			    "%s conf version 2 with %d densities has %d items"
1760 			    " should have %d",
1761 			    conf_name, ndens, list_len, 13 + ndens);
1762 		}
1763 
1764 		limit++;
1765 		for (dens = 0; dens < ndens && count; dens++) {
1766 			count--;
1767 			list++;
1768 			value = *list;
1769 			if (value < limit->bottom) {
1770 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1771 				    "%s density[%d] value too low: value ="
1772 				    " 0x%X limit 0x%X\n",
1773 				    conf_name, dens, value, limit->bottom);
1774 			} else if (value > limit->top) {
1775 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1776 				    "%s density[%d] value too high: value ="
1777 				    " 0x%X limit 0x%X\n",
1778 				    conf_name, dens, value, limit->top);
1779 			} else {
1780 				ST_DEBUG3(ST_DEVINFO, st_label, CE_CONT,
1781 				    "%s density[%d] value = 0x%X\n",
1782 				    conf_name, dens, value);
1783 			}
1784 		}
1785 	}
1786 
1787 	return (0);
1788 }
1789 
1790 static int
1791 st_get_conf_from_st_dot_conf(struct scsi_tape *un, char *vidpid,
1792     struct st_drivetype *dp)
1793 {
1794 	caddr_t config_list = NULL;
1795 	caddr_t data_list = NULL;
1796 	int	*data_ptr;
1797 	caddr_t vidptr, prettyptr, datanameptr;
1798 	size_t	vidlen, prettylen, datanamelen, tripletlen = 0;
1799 	int config_list_len, data_list_len, len, i;
1800 	int version;
1801 	int found = 0;
1802 
1803 	ST_FUNC(ST_DEVINFO, st_get_conf_from_st_dot_conf);
1804 
1805 	/*
1806 	 * Determine type of tape controller. Type is determined by
1807 	 * checking the vendor ids of the earlier inquiry command and
1808 	 * comparing those with vids in tape-config-list defined in st.conf
1809 	 */
1810 	if (ddi_getlongprop(DDI_DEV_T_ANY, ST_DEVINFO, DDI_PROP_DONTPASS,
1811 	    "tape-config-list", (caddr_t)&config_list, &config_list_len)
1812 	    != DDI_PROP_SUCCESS) {
1813 		return (found);
1814 	}
1815 
1816 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
1817 	    "st_get_conf_from_st_dot_conf(): st.conf has tape-config-list\n");
1818 
1819 	/*
1820 	 * Compare vids in each triplet - if it matches, get value for
1821 	 * data_name and contruct a st_drivetype struct
1822 	 * tripletlen is not set yet!
1823 	 */
1824 	for (len = config_list_len, vidptr = config_list;
1825 	    len > 0;
1826 	    vidptr += tripletlen, len -= tripletlen) {
1827 
1828 		vidlen = strlen(vidptr);
1829 		prettyptr = vidptr + vidlen + 1;
1830 		prettylen = strlen(prettyptr);
1831 		datanameptr = prettyptr + prettylen + 1;
1832 		datanamelen = strlen(datanameptr);
1833 		tripletlen = vidlen + prettylen + datanamelen + 3;
1834 
1835 		if (vidlen == 0) {
1836 			continue;
1837 		}
1838 
1839 		/*
1840 		 * If inquiry vid dosen't match this triplets vid,
1841 		 * try the next.
1842 		 */
1843 		if (strncasecmp(vidpid, vidptr, vidlen)) {
1844 			continue;
1845 		}
1846 
1847 		/*
1848 		 * if prettylen is zero then use the vid string
1849 		 */
1850 		if (prettylen == 0) {
1851 			prettyptr = vidptr;
1852 			prettylen = vidlen;
1853 		}
1854 
1855 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1856 		    "vid = %s, pretty=%s, dataname = %s\n",
1857 		    vidptr, prettyptr, datanameptr);
1858 
1859 		/*
1860 		 * get the data list
1861 		 */
1862 		if (ddi_getlongprop(DDI_DEV_T_ANY, ST_DEVINFO, 0,
1863 		    datanameptr, (caddr_t)&data_list,
1864 		    &data_list_len) != DDI_PROP_SUCCESS) {
1865 			/*
1866 			 * Error in getting property value
1867 			 * print warning!
1868 			 */
1869 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
1870 			    "data property (%s) has no value\n",
1871 			    datanameptr);
1872 			continue;
1873 		}
1874 
1875 		/*
1876 		 * now initialize the st_drivetype struct
1877 		 */
1878 		(void) strncpy(dp->name, prettyptr, ST_NAMESIZE - 1);
1879 		dp->length = (int)min(vidlen, (VIDPIDLEN - 1));
1880 		(void) strncpy(dp->vid, vidptr, dp->length);
1881 		data_ptr = (int *)data_list;
1882 		/*
1883 		 * check if data is enough for version, type,
1884 		 * bsize, options, # of densities, density1,
1885 		 * density2, ..., default_density
1886 		 */
1887 		if ((data_list_len < 5 * sizeof (int)) ||
1888 		    (data_list_len < 6 * sizeof (int) +
1889 		    *(data_ptr + 4) * sizeof (int))) {
1890 			/*
1891 			 * print warning and skip to next triplet.
1892 			 */
1893 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
1894 			    "data property (%s) incomplete\n",
1895 			    datanameptr);
1896 			kmem_free(data_list, data_list_len);
1897 			continue;
1898 		}
1899 
1900 		if (st_validate_conf_data(un, data_ptr,
1901 		    data_list_len / sizeof (int), datanameptr)) {
1902 			kmem_free(data_list, data_list_len);
1903 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
1904 			    "data property (%s) rejected\n",
1905 			    datanameptr);
1906 			continue;
1907 		}
1908 
1909 		/*
1910 		 * check version
1911 		 */
1912 		version = *data_ptr++;
1913 		if (version != 1 && version != 2) {
1914 			/* print warning but accept it */
1915 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
1916 			    "Version # for data property (%s) "
1917 			    "not set to 1 or 2\n", datanameptr);
1918 		}
1919 
1920 		dp->type    = *data_ptr++;
1921 		dp->bsize   = *data_ptr++;
1922 		dp->options = *data_ptr++;
1923 		dp->options |= ST_DYNAMIC;
1924 		len = *data_ptr++;
1925 		for (i = 0; i < NDENSITIES; i++) {
1926 			if (i < len) {
1927 				dp->densities[i] = *data_ptr++;
1928 			}
1929 		}
1930 		dp->default_density = *data_ptr << 3;
1931 		if (version == 2 &&
1932 		    data_list_len >= (13 + len) * sizeof (int)) {
1933 			data_ptr++;
1934 			dp->non_motion_timeout	= *data_ptr++;
1935 			dp->io_timeout		= *data_ptr++;
1936 			dp->rewind_timeout	= *data_ptr++;
1937 			dp->space_timeout	= *data_ptr++;
1938 			dp->load_timeout	= *data_ptr++;
1939 			dp->unload_timeout	= *data_ptr++;
1940 			dp->erase_timeout	= *data_ptr++;
1941 		}
1942 		kmem_free(data_list, data_list_len);
1943 		found = 1;
1944 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1945 		    "found in st.conf: vid = %s, pretty=%s\n",
1946 		    dp->vid, dp->name);
1947 		break;
1948 	}
1949 
1950 	/*
1951 	 * free up the memory allocated by ddi_getlongprop
1952 	 */
1953 	if (config_list) {
1954 		kmem_free(config_list, config_list_len);
1955 	}
1956 	return (found);
1957 }
1958 
1959 static int
1960 st_get_conf_from_st_conf_dot_c(struct scsi_tape *un, char *vidpid,
1961     struct st_drivetype *dp)
1962 {
1963 	int i;
1964 
1965 	ST_FUNC(ST_DEVINFO, st_get_conf_from_st_conf_dot_c);
1966 	/*
1967 	 * Determine type of tape controller.  Type is determined by
1968 	 * checking the result of the earlier inquiry command and
1969 	 * comparing vendor ids with strings in a table declared in st_conf.c.
1970 	 */
1971 	ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
1972 	    "st_get_conf_from_st_conf_dot_c(): looking at st_drivetypes\n");
1973 
1974 	for (i = 0; i < st_ndrivetypes; i++) {
1975 		if (st_drivetypes[i].length == 0) {
1976 			continue;
1977 		}
1978 		if (strncasecmp(vidpid, st_drivetypes[i].vid,
1979 		    st_drivetypes[i].length)) {
1980 			continue;
1981 		}
1982 		bcopy(&st_drivetypes[i], dp, sizeof (st_drivetypes[i]));
1983 		return (1);
1984 	}
1985 	return (0);
1986 }
1987 
1988 static int
1989 st_get_default_conf(struct scsi_tape *un, char *vidpid, struct st_drivetype *dp)
1990 {
1991 	int i;
1992 
1993 	ST_FUNC(ST_DEVINFO, st_get_default_conf);
1994 
1995 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
1996 	    "st_get_default_conf(): making drivetype from INQ cmd\n");
1997 
1998 
1999 	/*
2000 	 * Make up a name
2001 	 */
2002 	bcopy("Vendor '", dp->name, 8);
2003 	bcopy(vidpid, &dp->name[8], VIDLEN);
2004 	bcopy("' Product '", &dp->name[16], 11);
2005 	bcopy(&vidpid[8], &dp->name[27], PIDLEN);
2006 	dp->name[ST_NAMESIZE - 2] = '\'';
2007 	dp->name[ST_NAMESIZE - 1] = '\0';
2008 	dp->length = min(strlen(ST_INQUIRY->inq_vid), (VIDPIDLEN - 1));
2009 	(void) strncpy(dp->vid, ST_INQUIRY->inq_vid, dp->length);
2010 	/*
2011 	 * 'clean' vendor and product strings of non-printing chars
2012 	 */
2013 	for (i = 0; i < ST_NAMESIZE - 2; i++) {
2014 		if (dp->name[i] < ' ' || dp->name[i] > '~') {
2015 			dp->name[i] = '.';
2016 		}
2017 	}
2018 	dp->type = ST_TYPE_INVALID;
2019 	dp->options |= (ST_DYNAMIC | ST_UNLOADABLE | ST_MODE_SEL_COMP);
2020 
2021 	return (1); /* Can Not Fail */
2022 }
2023 
2024 /*
2025  * Regular Unix Entry points
2026  */
2027 
2028 
2029 
2030 /* ARGSUSED */
2031 static int
2032 st_open(dev_t *dev_p, int flag, int otyp, cred_t *cred_p)
2033 {
2034 	dev_t dev = *dev_p;
2035 	int rval = 0;
2036 
2037 	GET_SOFT_STATE(dev);
2038 
2039 	ST_ENTR(ST_DEVINFO, st_open);
2040 
2041 	/*
2042 	 * validate that we are addressing a sensible unit
2043 	 */
2044 	mutex_enter(ST_MUTEX);
2045 
2046 #ifdef	STDEBUG
2047 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2048 	    "st_open(node = %s dev = 0x%lx, flag = %d, otyp = %d)\n",
2049 	    st_dev_name(dev), *dev_p, flag, otyp);
2050 #endif
2051 
2052 	/*
2053 	 * All device accesss go thru st_strategy() where we check
2054 	 * suspend status
2055 	 */
2056 
2057 	if (!un->un_attached) {
2058 		st_known_tape_type(un);
2059 		if (!un->un_attached) {
2060 			rval = ENXIO;
2061 			goto exit;
2062 		}
2063 
2064 	}
2065 
2066 	/*
2067 	 * Check for the case of the tape in the middle of closing.
2068 	 * This isn't simply a check of the current state, because
2069 	 * we could be in state of sensing with the previous state
2070 	 * that of closing.
2071 	 *
2072 	 * And don't allow multiple opens.
2073 	 */
2074 	if (!(flag & (FNDELAY | FNONBLOCK)) && IS_CLOSING(un)) {
2075 		un->un_laststate = un->un_state;
2076 		un->un_state = ST_STATE_CLOSE_PENDING_OPEN;
2077 		while (IS_CLOSING(un) ||
2078 		    un->un_state == ST_STATE_CLOSE_PENDING_OPEN) {
2079 			if (cv_wait_sig(&un->un_clscv, ST_MUTEX) == 0) {
2080 				rval = EINTR;
2081 				un->un_state = un->un_laststate;
2082 				goto exit;
2083 			}
2084 		}
2085 	} else if (un->un_state != ST_STATE_CLOSED) {
2086 		rval = EBUSY;
2087 		goto busy;
2088 	}
2089 
2090 	/*
2091 	 * record current dev
2092 	 */
2093 	un->un_dev = dev;
2094 	un->un_oflags = flag;	/* save for use in st_tape_init() */
2095 	un->un_errno = 0;	/* no errors yet */
2096 	un->un_restore_pos = 0;
2097 	un->un_rqs_state = 0;
2098 
2099 	/*
2100 	 * If we are opening O_NDELAY, or O_NONBLOCK, we don't check for
2101 	 * anything, leave internal states alone, if fileno >= 0
2102 	 */
2103 	if (flag & (FNDELAY | FNONBLOCK)) {
2104 		switch (un->un_pos.pmode) {
2105 
2106 		case invalid:
2107 			un->un_state = ST_STATE_OFFLINE;
2108 			break;
2109 
2110 		case legacy:
2111 			/*
2112 			 * If position is anything other than rewound.
2113 			 */
2114 			if (un->un_pos.fileno != 0 || un->un_pos.blkno != 0) {
2115 				/*
2116 				 * set un_read_only/write-protect status.
2117 				 *
2118 				 * If the tape is not bot we can assume
2119 				 * that mspl->wp_status is set properly.
2120 				 * else
2121 				 * we need to do a mode sense/Tur once
2122 				 * again to get the actual tape status.(since
2123 				 * user might have replaced the tape)
2124 				 * Hence make the st state OFFLINE so that
2125 				 * we re-intialize the tape once again.
2126 				 */
2127 				un->un_read_only =
2128 				    (un->un_oflags & FWRITE) ? RDWR : RDONLY;
2129 				un->un_state = ST_STATE_OPEN_PENDING_IO;
2130 			} else {
2131 				un->un_state = ST_STATE_OFFLINE;
2132 			}
2133 			break;
2134 		case logical:
2135 			/* swag not sure how we were open last time */
2136 			(void) st_update_block_pos(un);
2137 			if (un->un_pos.lgclblkno == 0) {
2138 				un->un_state = ST_STATE_OFFLINE;
2139 			} else {
2140 				un->un_read_only =
2141 				    (un->un_oflags & FWRITE) ? 0 : 1;
2142 				un->un_state = ST_STATE_OPEN_PENDING_IO;
2143 			}
2144 			break;
2145 		}
2146 		rval = 0;
2147 	} else {
2148 		/*
2149 		 * Not opening O_NDELAY.
2150 		 */
2151 		un->un_state = ST_STATE_OPENING;
2152 
2153 		rval = st_tape_init(dev);
2154 		if ((rval == EACCES) && (un->un_read_only & WORM)) {
2155 			un->un_state = ST_STATE_OPEN_PENDING_IO;
2156 			rval = 0; /* so open doesn't fail */
2157 		} else if (rval) {
2158 			/*
2159 			 * Release the tape unit, if reserved and not
2160 			 * preserve reserve.
2161 			 */
2162 			if ((un->un_rsvd_status &
2163 			    (ST_RESERVE | ST_PRESERVE_RESERVE)) == ST_RESERVE) {
2164 				(void) st_reserve_release(un, ST_RELEASE);
2165 			}
2166 		} else {
2167 			un->un_state = ST_STATE_OPEN_PENDING_IO;
2168 		}
2169 	}
2170 
2171 exit:
2172 	/*
2173 	 * we don't want any uninvited guests scrogging our data when we're
2174 	 * busy with something, so for successful opens or failed opens
2175 	 * (except for EBUSY), reset these counters and state appropriately.
2176 	 */
2177 	if (rval != EBUSY) {
2178 		if (rval) {
2179 			un->un_state = ST_STATE_CLOSED;
2180 		}
2181 		un->un_err_resid = 0;
2182 		un->un_retry_ct = 0;
2183 		un->un_tran_retry_ct = 0;
2184 	}
2185 busy:
2186 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2187 	    "st_open: return val = %x, state = %d\n", rval, un->un_state);
2188 	mutex_exit(ST_MUTEX);
2189 	return (rval);
2190 
2191 }
2192 
2193 static int
2194 st_tape_init(dev_t dev)
2195 {
2196 	int err;
2197 	int rval = 0;
2198 
2199 	GET_SOFT_STATE(dev);
2200 
2201 	ST_FUNC(ST_DEVINFO, st_tape_init);
2202 
2203 	ASSERT(mutex_owned(ST_MUTEX));
2204 
2205 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2206 	    "st_tape_init(dev = 0x%lx, oflags = %d)\n", dev, un->un_oflags);
2207 
2208 	/*
2209 	 * Clean up after any errors left by 'last' close.
2210 	 * This also handles the case of the initial open.
2211 	 */
2212 	if (un->un_state != ST_STATE_INITIALIZING) {
2213 		un->un_laststate = un->un_state;
2214 		un->un_state = ST_STATE_OPENING;
2215 	}
2216 
2217 	un->un_kbytes_xferred = 0;
2218 
2219 	/*
2220 	 * do a throw away TUR to clear check condition
2221 	 */
2222 	err = st_cmd(dev, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
2223 
2224 	/*
2225 	 * If test unit ready fails because the drive is reserved
2226 	 * by another host fail the open for no access.
2227 	 */
2228 	if (err) {
2229 		if (un->un_rsvd_status & ST_RESERVATION_CONFLICT) {
2230 			un->un_state = ST_STATE_CLOSED;
2231 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
2232 			    "st_tape_init: RESERVATION CONFLICT\n");
2233 			rval = EACCES;
2234 			goto exit;
2235 		}
2236 	}
2237 
2238 	/*
2239 	 * See whether this is a generic device that we haven't figured
2240 	 * anything out about yet.
2241 	 */
2242 	if (un->un_dp->type == ST_TYPE_INVALID) {
2243 		rval = st_determine_generic(dev);
2244 		if (rval) {
2245 			if (rval != EACCES) {
2246 				rval = EIO;
2247 			}
2248 			un->un_state = ST_STATE_CLOSED;
2249 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2250 			    "st_tape_init: %s invalid type\n",
2251 			    rval == EACCES ? "EACCES" : "EIO");
2252 			goto exit;
2253 		}
2254 		/*
2255 		 * If this is a Unknown Type drive,
2256 		 * Use the READ BLOCK LIMITS to determine if
2257 		 * allow large xfer is approprate if not globally
2258 		 * disabled with st_allow_large_xfer.
2259 		 */
2260 		un->un_allow_large_xfer = (uchar_t)st_allow_large_xfer;
2261 	} else {
2262 
2263 		/*
2264 		 * If we allow_large_xfer (ie >64k) and have not yet found out
2265 		 * the max block size supported by the drive,
2266 		 * find it by issueing a READ_BLKLIM command.
2267 		 * if READ_BLKLIM cmd fails, assume drive doesn't
2268 		 * allow_large_xfer and min/max block sizes as 1 byte and 63k.
2269 		 */
2270 		un->un_allow_large_xfer = st_allow_large_xfer &&
2271 		    (un->un_dp->options & ST_NO_RECSIZE_LIMIT);
2272 	}
2273 	/*
2274 	 * if maxbsize is unknown, set the maximum block size.
2275 	 */
2276 	if (un->un_maxbsize == MAXBSIZE_UNKNOWN) {
2277 
2278 		/*
2279 		 * Get the Block limits of the tape drive.
2280 		 * if un->un_allow_large_xfer = 0 , then make sure
2281 		 * that maxbsize is <= ST_MAXRECSIZE_FIXED.
2282 		 */
2283 		un->un_rbl = kmem_zalloc(RBLSIZE, KM_SLEEP);
2284 
2285 		err = st_cmd(dev, SCMD_READ_BLKLIM, RBLSIZE, SYNC_CMD);
2286 		if (err) {
2287 			/* Retry */
2288 			err = st_cmd(dev, SCMD_READ_BLKLIM, RBLSIZE, SYNC_CMD);
2289 		}
2290 		if (!err) {
2291 
2292 			/*
2293 			 * if cmd successful, use limit returned
2294 			 */
2295 			un->un_maxbsize = (un->un_rbl->max_hi << 16) +
2296 			    (un->un_rbl->max_mid << 8) +
2297 			    un->un_rbl->max_lo;
2298 			un->un_minbsize = (un->un_rbl->min_hi << 8) +
2299 			    un->un_rbl->min_lo;
2300 			un->un_data_mod = 1 << un->un_rbl->granularity;
2301 			if ((un->un_maxbsize == 0) ||
2302 			    (un->un_allow_large_xfer == 0 &&
2303 			    un->un_maxbsize > ST_MAXRECSIZE_FIXED)) {
2304 				un->un_maxbsize = ST_MAXRECSIZE_FIXED;
2305 
2306 			} else if (un->un_dp->type == ST_TYPE_DEFAULT) {
2307 				/*
2308 				 * Drive is not one that is configured, But the
2309 				 * READ BLOCK LIMITS tells us it can do large
2310 				 * xfers.
2311 				 */
2312 				if (un->un_maxbsize > ST_MAXRECSIZE_FIXED) {
2313 					un->un_dp->options |=
2314 					    ST_NO_RECSIZE_LIMIT;
2315 				}
2316 				/*
2317 				 * If max and mimimum block limits are the
2318 				 * same this is a fixed block size device.
2319 				 */
2320 				if (un->un_maxbsize == un->un_minbsize) {
2321 					un->un_dp->options &= ~ST_VARIABLE;
2322 				}
2323 			}
2324 
2325 			if (un->un_minbsize == 0) {
2326 				un->un_minbsize = 1;
2327 			}
2328 
2329 		} else { /* error on read block limits */
2330 
2331 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2332 			    "!st_tape_init: Error on READ BLOCK LIMITS,"
2333 			    " errno = %d un_rsvd_status = 0x%X\n",
2334 			    err, un->un_rsvd_status);
2335 
2336 			/*
2337 			 * since read block limits cmd failed,
2338 			 * do not allow large xfers.
2339 			 * use old values in st_minphys
2340 			 */
2341 			if (un->un_rsvd_status & ST_RESERVATION_CONFLICT) {
2342 				rval = EACCES;
2343 			} else {
2344 				un->un_allow_large_xfer = 0;
2345 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2346 				    "!Disabling large transfers\n");
2347 
2348 				/*
2349 				 * we guess maxbsize and minbsize
2350 				 */
2351 				if (un->un_bsize) {
2352 					un->un_maxbsize = un->un_minbsize =
2353 					    un->un_bsize;
2354 				} else {
2355 					un->un_maxbsize = ST_MAXRECSIZE_FIXED;
2356 					un->un_minbsize = 1;
2357 				}
2358 				/*
2359 				 * Data Mod must be set,
2360 				 * Even if read block limits fails.
2361 				 * Prevents Divide By Zero in st_rw().
2362 				 */
2363 				un->un_data_mod = 1;
2364 			}
2365 		}
2366 		if (un->un_rbl) {
2367 			kmem_free(un->un_rbl, RBLSIZE);
2368 			un->un_rbl = NULL;
2369 		}
2370 
2371 		if (rval) {
2372 			goto exit;
2373 		}
2374 	}
2375 
2376 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
2377 	    "maxdma = %d, maxbsize = %d, minbsize = %d, %s large xfer\n",
2378 	    un->un_maxdma, un->un_maxbsize, un->un_minbsize,
2379 	    (un->un_allow_large_xfer ? "ALLOW": "DON'T ALLOW"));
2380 
2381 	err = st_cmd(dev, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
2382 
2383 	if (err != 0) {
2384 		if (err == EINTR) {
2385 			un->un_laststate = un->un_state;
2386 			un->un_state = ST_STATE_CLOSED;
2387 			rval = EINTR;
2388 			goto exit;
2389 		}
2390 		/*
2391 		 * Make sure the tape is ready
2392 		 */
2393 		un->un_pos.pmode = invalid;
2394 		if (un->un_status != KEY_UNIT_ATTENTION) {
2395 			/*
2396 			 * allow open no media.  Subsequent MTIOCSTATE
2397 			 * with media present will complete the open
2398 			 * logic.
2399 			 */
2400 			un->un_laststate = un->un_state;
2401 			if (un->un_oflags & (FNONBLOCK|FNDELAY)) {
2402 				un->un_mediastate = MTIO_EJECTED;
2403 				un->un_state = ST_STATE_OFFLINE;
2404 				rval = 0;
2405 				goto exit;
2406 			} else {
2407 				un->un_state = ST_STATE_CLOSED;
2408 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2409 				    "st_tape_init EIO no media, not opened "
2410 				    "O_NONBLOCK|O_EXCL\n");
2411 				rval = EIO;
2412 				goto exit;
2413 			}
2414 		}
2415 	}
2416 
2417 	/*
2418 	 * On each open, initialize block size from drivetype struct,
2419 	 * as it could have been changed by MTSRSZ ioctl.
2420 	 * Now, ST_VARIABLE simply means drive is capable of variable
2421 	 * mode. All drives are assumed to support fixed records.
2422 	 * Hence, un_bsize tells what mode the drive is in.
2423 	 *	un_bsize	= 0	- variable record length
2424 	 *			= x	- fixed record length is x
2425 	 */
2426 	un->un_bsize = un->un_dp->bsize;
2427 
2428 	/*
2429 	 * If saved position is valid go there
2430 	 */
2431 	if (un->un_restore_pos) {
2432 		rval = st_validate_tapemarks(un, &un->un_pos);
2433 		if (rval != 0) {
2434 			if (rval != EACCES) {
2435 				rval = EIO;
2436 			}
2437 			un->un_restore_pos = 0;
2438 			un->un_laststate = un->un_state;
2439 			un->un_state = ST_STATE_CLOSED;
2440 			goto exit;
2441 		}
2442 		un->un_pos.fileno = un->un_save_fileno;
2443 		un->un_pos.blkno = un->un_save_blkno;
2444 		un->un_restore_pos = 0;
2445 	}
2446 
2447 	if (un->un_pos.pmode == invalid) {
2448 		rval = st_loadtape(dev);
2449 		if (rval) {
2450 			if (rval != EACCES) {
2451 				rval = EIO;
2452 			}
2453 			un->un_laststate = un->un_state;
2454 			un->un_state = ST_STATE_CLOSED;
2455 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2456 			    "st_tape_init: %s can't open tape\n",
2457 			    rval == EACCES ? "EACCES" : "EIO");
2458 			goto exit;
2459 		}
2460 	}
2461 
2462 	/*
2463 	 * do a mode sense to pick up state of current write-protect,
2464 	 * Could cause reserve and fail due to conflict.
2465 	 */
2466 	rval = st_modesense(un);
2467 	if (rval == EACCES) {
2468 		goto exit;
2469 	}
2470 
2471 	/*
2472 	 * If we are opening the tape for writing, check
2473 	 * to make sure that the tape can be written.
2474 	 */
2475 	if (un->un_oflags & FWRITE) {
2476 		err = 0;
2477 		if (un->un_mspl->wp) {
2478 			un->un_status = KEY_WRITE_PROTECT;
2479 			un->un_laststate = un->un_state;
2480 			un->un_state = ST_STATE_CLOSED;
2481 			rval = EACCES;
2482 			/*
2483 			 * STK sets the wp bit if volsafe tape is loaded.
2484 			 */
2485 			if ((un->un_dp->type == MT_ISSTK9840) &&
2486 			    (un->un_dp->options & ST_WORMABLE)) {
2487 				un->un_read_only = RDONLY;
2488 			} else {
2489 				goto exit;
2490 			}
2491 		} else {
2492 			un->un_read_only = RDWR;
2493 		}
2494 	} else {
2495 		un->un_read_only = RDONLY;
2496 	}
2497 
2498 	if (un->un_dp->options & ST_WORMABLE) {
2499 		un->un_read_only |= un->un_wormable(un);
2500 
2501 		if (((un->un_read_only == WORM) ||
2502 		    (un->un_read_only == RDWORM)) &&
2503 		    ((un->un_oflags & FWRITE) == FWRITE)) {
2504 			un->un_status = KEY_DATA_PROTECT;
2505 			rval = EACCES;
2506 			ST_DEBUG4(ST_DEVINFO, st_label, CE_NOTE,
2507 			    "read_only = %d eof = %d oflag = %d\n",
2508 			    un->un_read_only, un->un_pos.eof, un->un_oflags);
2509 		}
2510 	}
2511 
2512 	/*
2513 	 * If we're opening the tape write-only, we need to
2514 	 * write 2 filemarks on the HP 1/2 inch drive, to
2515 	 * create a null file.
2516 	 */
2517 	if ((un->un_read_only == RDWR) ||
2518 	    (un->un_read_only == WORM) && (un->un_oflags & FWRITE)) {
2519 		if (un->un_dp->options & ST_REEL) {
2520 			un->un_fmneeded = 2;
2521 		} else {
2522 			un->un_fmneeded = 1;
2523 		}
2524 	} else {
2525 		un->un_fmneeded = 0;
2526 	}
2527 
2528 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
2529 	    "fmneeded = %x\n", un->un_fmneeded);
2530 
2531 	/*
2532 	 * Make sure the density can be selected correctly.
2533 	 * If WORM can only write at the append point which in most cases
2534 	 * isn't BOP. st_determine_density() with a B_WRITE only attempts
2535 	 * to set and try densities if a BOP.
2536 	 */
2537 	if (st_determine_density(dev,
2538 	    un->un_read_only == RDWR ? B_WRITE : B_READ)) {
2539 		un->un_status = KEY_ILLEGAL_REQUEST;
2540 		un->un_laststate = un->un_state;
2541 		un->un_state = ST_STATE_CLOSED;
2542 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
2543 		    "st_tape_init: EIO can't determine density\n");
2544 		rval = EIO;
2545 		goto exit;
2546 	}
2547 
2548 	/*
2549 	 * Destroy the knowledge that we have 'determined'
2550 	 * density so that a later read at BOT comes along
2551 	 * does the right density determination.
2552 	 */
2553 
2554 	un->un_density_known = 0;
2555 
2556 
2557 	/*
2558 	 * Okay, the tape is loaded and either at BOT or somewhere past.
2559 	 * Mark the state such that any I/O or tape space operations
2560 	 * will get/set the right density, etc..
2561 	 */
2562 	un->un_laststate = un->un_state;
2563 	un->un_lastop = ST_OP_NIL;
2564 	un->un_mediastate = MTIO_INSERTED;
2565 	cv_broadcast(&un->un_state_cv);
2566 
2567 	/*
2568 	 *  Set test append flag if writing.
2569 	 *  First write must check that tape is positioned correctly.
2570 	 */
2571 	un->un_test_append = (un->un_oflags & FWRITE);
2572 
2573 exit:
2574 	un->un_err_resid = 0;
2575 	un->un_last_resid = 0;
2576 	un->un_last_count = 0;
2577 
2578 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
2579 	    "st_tape_init: return val = %x\n", rval);
2580 	return (rval);
2581 
2582 }
2583 
2584 
2585 
2586 /* ARGSUSED */
2587 static int
2588 st_close(dev_t dev, int flag, int otyp, cred_t *cred_p)
2589 {
2590 	int err = 0;
2591 	int norew, count, last_state;
2592 #if defined(__i386) || defined(__amd64)
2593 	struct contig_mem *cp, *cp_temp;
2594 #endif
2595 
2596 	GET_SOFT_STATE(dev);
2597 
2598 	ST_ENTR(ST_DEVINFO, st_close);
2599 
2600 	/*
2601 	 * wait till all cmds in the pipeline have been completed
2602 	 */
2603 	mutex_enter(ST_MUTEX);
2604 
2605 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2606 	    "st_close(dev = 0x%lx, flag = %d, otyp = %d)\n", dev, flag, otyp);
2607 
2608 	st_wait_for_io(un);
2609 
2610 	/* turn off persistent errors on close, as we want close to succeed */
2611 	TURN_PE_OFF(un);
2612 
2613 	/*
2614 	 * set state to indicate that we are in process of closing
2615 	 */
2616 	last_state = un->un_laststate = un->un_state;
2617 	un->un_state = ST_STATE_CLOSING;
2618 
2619 	/*
2620 	 * BSD behavior:
2621 	 * a close always causes a silent span to the next file if we've hit
2622 	 * an EOF (but not yet read across it).
2623 	 */
2624 #ifdef DEBUG
2625 	if ((st_debug & 0xf) >= 6)
2626 		st_print_position(un, "st_close1:", &un->un_pos);
2627 #endif
2628 
2629 	if (BSD_BEHAVIOR && (un->un_pos.eof == ST_EOF)) {
2630 		if (un->un_pos.pmode != invalid) {
2631 			un->un_pos.fileno++;
2632 			un->un_pos.blkno = 0;
2633 		}
2634 		un->un_pos.eof = ST_NO_EOF;
2635 	}
2636 
2637 	/*
2638 	 * rewinding?
2639 	 */
2640 	norew = (getminor(dev) & MT_NOREWIND);
2641 
2642 	/*
2643 	 * SVR4 behavior for skipping to next file:
2644 	 *
2645 	 * If we have not seen a filemark, space to the next file
2646 	 *
2647 	 * If we have already seen the filemark we are physically in the next
2648 	 * file and we only increment the filenumber
2649 	 */
2650 
2651 
2652 	if (norew && SVR4_BEHAVIOR && (flag & FREAD) &&
2653 	    (un->un_pos.blkno != 0) &&
2654 	    ((un->un_lastop != ST_OP_WRITE) && (un->un_lastop != ST_OP_WEOF))) {
2655 		switch (un->un_pos.eof) {
2656 		case ST_NO_EOF:
2657 			/*
2658 			 * if we were reading and did not read the complete file
2659 			 * skip to the next file, leaving the tape correctly
2660 			 * positioned to read the first record of the next file
2661 			 * Check first for REEL if we are at EOT by trying to
2662 			 * read a block
2663 			 */
2664 			if ((un->un_dp->options & ST_REEL) &&
2665 			    (!(un->un_dp->options & ST_READ_IGNORE_EOFS)) &&
2666 			    (un->un_pos.blkno == 0)) {
2667 				if (st_cmd(dev, SCMD_SPACE, Blk(1), SYNC_CMD)) {
2668 					ST_DEBUG2(ST_DEVINFO, st_label,
2669 					    SCSI_DEBUG,
2670 					    "st_close : EIO can't space\n");
2671 					err = EIO;
2672 					break;
2673 				}
2674 				if (un->un_pos.eof >= ST_EOF_PENDING) {
2675 					un->un_pos.eof = ST_EOT_PENDING;
2676 					un->un_pos.fileno += 1;
2677 					un->un_pos.blkno   = 0;
2678 					break;
2679 				}
2680 			}
2681 			if (st_cmd(dev, SCMD_SPACE, Fmk(1), SYNC_CMD)) {
2682 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2683 				    "st_close: EIO can't space #2\n");
2684 				err = EIO;
2685 			} else {
2686 				ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
2687 				    "st_close2: fileno=%x,blkno=%x,eof=%x\n",
2688 				    un->un_pos.fileno, un->un_pos.blkno,
2689 				    un->un_pos.eof);
2690 				un->un_pos.eof = ST_NO_EOF;
2691 			}
2692 			break;
2693 
2694 		case ST_EOF_PENDING:
2695 		case ST_EOF:
2696 			un->un_pos.fileno += 1;
2697 			un->un_pos.blkno   = 0;
2698 			un->un_pos.eof = ST_NO_EOF;
2699 			break;
2700 
2701 		case ST_EOT:
2702 		case ST_EOT_PENDING:
2703 			/* nothing to do */
2704 			break;
2705 		default:
2706 			scsi_log(ST_DEVINFO, st_label, CE_PANIC,
2707 			    "Undefined state 0x%x", un->un_pos.eof);
2708 
2709 		}
2710 	}
2711 
2712 
2713 	/*
2714 	 * For performance reasons (HP 88780), the driver should
2715 	 * postpone writing the second tape mark until just before a file
2716 	 * positioning ioctl is issued (e.g., rewind).	This means that
2717 	 * the user must not manually rewind the tape because the tape will
2718 	 * be missing the second tape mark which marks EOM.
2719 	 * However, this small performance improvement is not worth the risk.
2720 	 */
2721 
2722 	/*
2723 	 * We need to back up over the filemark we inadvertently popped
2724 	 * over doing a read in between the two filemarks that constitute
2725 	 * logical eot for 1/2" tapes. Note that ST_EOT_PENDING is only
2726 	 * set while reading.
2727 	 *
2728 	 * If we happen to be at physical eot (ST_EOM) (writing case),
2729 	 * the writing of filemark(s) will clear the ST_EOM state, which
2730 	 * we don't want, so we save this state and restore it later.
2731 	 */
2732 
2733 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
2734 	    "flag=%x, fmneeded=%x, lastop=%x, eof=%x\n",
2735 	    flag, un->un_fmneeded, un->un_lastop, un->un_pos.eof);
2736 
2737 	if (un->un_pos.eof == ST_EOT_PENDING) {
2738 		if (norew) {
2739 			if (st_cmd(dev, SCMD_SPACE, Fmk((-1)), SYNC_CMD)) {
2740 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2741 				    "st_close: EIO can't space #3\n");
2742 				err = EIO;
2743 			} else {
2744 				un->un_pos.blkno = 0;
2745 				un->un_pos.eof = ST_EOT;
2746 			}
2747 		} else {
2748 			un->un_pos.eof = ST_NO_EOF;
2749 		}
2750 
2751 	/*
2752 	 * Do we need to write a file mark?
2753 	 *
2754 	 * only write filemarks if there are fmks to be written and
2755 	 *   - open for write (possibly read/write)
2756 	 *   - the last operation was a write
2757 	 * or:
2758 	 *   -	opened for wronly
2759 	 *   -	no data was written
2760 	 */
2761 	} else if ((un->un_pos.pmode != invalid) && (un->un_fmneeded > 0) &&
2762 	    (((flag & FWRITE) && (un->un_lastop == ST_OP_WRITE)) ||
2763 	    ((flag & FWRITE) && (un->un_lastop == ST_OP_WEOF)) ||
2764 	    ((flag == FWRITE) && (un->un_lastop == ST_OP_NIL)))) {
2765 
2766 		/* save ST_EOM state */
2767 		int was_at_eom = (un->un_pos.eof == ST_EOM) ? 1 : 0;
2768 
2769 		/*
2770 		 * Note that we will write a filemark if we had opened
2771 		 * the tape write only and no data was written, thus
2772 		 * creating a null file.
2773 		 *
2774 		 * If the user already wrote one, we only have to write 1 more.
2775 		 * If they wrote two, we don't have to write any.
2776 		 */
2777 
2778 		count = un->un_fmneeded;
2779 		if (count > 0) {
2780 			if (st_cmd(dev, SCMD_WRITE_FILE_MARK,
2781 			    count, SYNC_CMD)) {
2782 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2783 				    "st_close : EIO can't wfm\n");
2784 				err = EIO;
2785 			}
2786 			if ((un->un_dp->options & ST_REEL) && norew) {
2787 				if (st_cmd(dev, SCMD_SPACE, Fmk((-1)),
2788 				    SYNC_CMD)) {
2789 					ST_DEBUG2(ST_DEVINFO, st_label,
2790 					    SCSI_DEBUG,
2791 					    "st_close : EIO space fmk(-1)\n");
2792 					err = EIO;
2793 				}
2794 				un->un_pos.eof = ST_NO_EOF;
2795 				/* fix up block number */
2796 				un->un_pos.blkno = 0;
2797 			}
2798 		}
2799 
2800 		/*
2801 		 * If we aren't going to be rewinding, and we were at
2802 		 * physical eot, restore the state that indicates we
2803 		 * are at physical eot. Once you have reached physical
2804 		 * eot, and you close the tape, the only thing you can
2805 		 * do on the next open is to rewind. Access to trailer
2806 		 * records is only allowed without closing the device.
2807 		 */
2808 		if (norew == 0 && was_at_eom) {
2809 			un->un_pos.eof = ST_EOM;
2810 		}
2811 	}
2812 
2813 	/*
2814 	 * report soft errors if enabled and available, if we never accessed
2815 	 * the drive, don't get errors. This will prevent some DAT error
2816 	 * messages upon LOG SENSE.
2817 	 */
2818 	if (st_report_soft_errors_on_close &&
2819 	    (un->un_dp->options & ST_SOFT_ERROR_REPORTING) &&
2820 	    (last_state != ST_STATE_OFFLINE)) {
2821 		(void) st_report_soft_errors(dev, flag);
2822 	}
2823 
2824 
2825 	/*
2826 	 * Do we need to rewind? Can we rewind?
2827 	 */
2828 	if (norew == 0 && un->un_pos.pmode != invalid && err == 0) {
2829 		/*
2830 		 * We'd like to rewind with the
2831 		 * 'immediate' bit set, but this
2832 		 * causes problems on some drives
2833 		 * where subsequent opens get a
2834 		 * 'NOT READY' error condition
2835 		 * back while the tape is rewinding,
2836 		 * which is impossible to distinguish
2837 		 * from the condition of 'no tape loaded'.
2838 		 *
2839 		 * Also, for some targets, if you disconnect
2840 		 * with the 'immediate' bit set, you don't
2841 		 * actually return right away, i.e., the
2842 		 * target ignores your request for immediate
2843 		 * return.
2844 		 *
2845 		 * Instead, we'll fire off an async rewind
2846 		 * command. We'll mark the device as closed,
2847 		 * and any subsequent open will stall on
2848 		 * the first TEST_UNIT_READY until the rewind
2849 		 * completes.
2850 		 */
2851 
2852 		/*
2853 		 * Used to be if reserve was not supported we'd send an
2854 		 * asynchronious rewind. Comments above may be slightly invalid
2855 		 * as the immediate bit was never set. Doing an immedate rewind
2856 		 * makes sense, I think fixes to not ready status might handle
2857 		 * the problems described above.
2858 		 */
2859 		if (un->un_sd->sd_inq->inq_ansi < 2) {
2860 			(void) st_cmd(dev, SCMD_REWIND, 0, SYNC_CMD);
2861 		} else {
2862 			(void) st_cmd(dev, SCMD_REWIND, 0, ASYNC_CMD);
2863 		}
2864 	}
2865 
2866 	/*
2867 	 * eject tape if necessary
2868 	 */
2869 	if (un->un_eject_tape_on_failure) {
2870 		un->un_eject_tape_on_failure = 0;
2871 		if (st_cmd(dev, SCMD_LOAD, LD_UNLOAD, SYNC_CMD)) {
2872 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2873 			    "st_close : can't unload tape\n");
2874 		} else {
2875 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2876 			    "st_close : tape unloaded \n");
2877 			un->un_pos.eof = ST_NO_EOF;
2878 			un->un_mediastate = MTIO_EJECTED;
2879 		}
2880 	}
2881 	/*
2882 	 * Release the tape unit, if default reserve/release
2883 	 * behaviour.
2884 	 */
2885 	if ((un->un_rsvd_status &
2886 	    (ST_RESERVE | ST_PRESERVE_RESERVE)) == ST_RESERVE) {
2887 		(void) st_reserve_release(un, ST_RELEASE);
2888 	}
2889 
2890 	/*
2891 	 * clear up state
2892 	 */
2893 	un->un_laststate = un->un_state;
2894 	un->un_state = ST_STATE_CLOSED;
2895 	un->un_lastop = ST_OP_NIL;
2896 	un->un_throttle = 1;	/* assume one request at time, for now */
2897 	un->un_retry_ct = 0;
2898 	un->un_tran_retry_ct = 0;
2899 	un->un_errno = 0;
2900 	un->un_swr_token = (opaque_t)NULL;
2901 	un->un_rsvd_status &= ~(ST_INIT_RESERVE);
2902 
2903 	/* Restore the options to the init time settings */
2904 	if (un->un_init_options & ST_READ_IGNORE_ILI) {
2905 		un->un_dp->options |= ST_READ_IGNORE_ILI;
2906 	} else {
2907 		un->un_dp->options &= ~ST_READ_IGNORE_ILI;
2908 	}
2909 
2910 	if (un->un_init_options & ST_READ_IGNORE_EOFS) {
2911 		un->un_dp->options |= ST_READ_IGNORE_EOFS;
2912 	} else {
2913 		un->un_dp->options &= ~ST_READ_IGNORE_EOFS;
2914 	}
2915 
2916 	if (un->un_init_options & ST_SHORT_FILEMARKS) {
2917 		un->un_dp->options |= ST_SHORT_FILEMARKS;
2918 	} else {
2919 		un->un_dp->options &= ~ST_SHORT_FILEMARKS;
2920 	}
2921 
2922 	ASSERT(mutex_owned(ST_MUTEX));
2923 
2924 	/*
2925 	 * Signal anyone awaiting a close operation to complete.
2926 	 */
2927 	cv_signal(&un->un_clscv);
2928 
2929 	/*
2930 	 * any kind of error on closing causes all state to be tossed
2931 	 */
2932 	if (err && un->un_status != KEY_ILLEGAL_REQUEST) {
2933 		/*
2934 		 * note that st_intr has already set
2935 		 * un_pos.pmode to invalid.
2936 		 */
2937 		un->un_density_known = 0;
2938 	}
2939 
2940 #if defined(__i386) || defined(__amd64)
2941 	/*
2942 	 * free any contiguous mem alloc'ed for big block I/O
2943 	 */
2944 	cp = un->un_contig_mem;
2945 	while (cp) {
2946 		if (cp->cm_addr) {
2947 			ddi_dma_mem_free(&cp->cm_acc_hdl);
2948 		}
2949 		cp_temp = cp;
2950 		cp = cp->cm_next;
2951 		kmem_free(cp_temp,
2952 		    sizeof (struct contig_mem) + biosize());
2953 	}
2954 	un->un_contig_mem_total_num = 0;
2955 	un->un_contig_mem_available_num = 0;
2956 	un->un_contig_mem = NULL;
2957 	un->un_max_contig_mem_len = 0;
2958 #endif
2959 
2960 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
2961 	    "st_close3: return val = %x, fileno=%x, blkno=%x, eof=%x\n",
2962 	    err, un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
2963 
2964 	mutex_exit(ST_MUTEX);
2965 	return (err);
2966 }
2967 
2968 /*
2969  * These routines perform raw i/o operations.
2970  */
2971 
2972 /* ARGSUSED2 */
2973 static int
2974 st_aread(dev_t dev, struct aio_req *aio, cred_t *cred_p)
2975 {
2976 #ifdef DEBUG
2977 	GET_SOFT_STATE(dev);
2978 	ST_ENTR(ST_DEVINFO, st_aread);
2979 #endif
2980 	return (st_arw(dev, aio, B_READ));
2981 }
2982 
2983 
2984 /* ARGSUSED2 */
2985 static int
2986 st_awrite(dev_t dev, struct aio_req *aio, cred_t *cred_p)
2987 {
2988 #ifdef DEBUG
2989 	GET_SOFT_STATE(dev);
2990 	ST_ENTR(ST_DEVINFO, st_awrite);
2991 #endif
2992 	return (st_arw(dev, aio, B_WRITE));
2993 }
2994 
2995 
2996 
2997 /* ARGSUSED */
2998 static int
2999 st_read(dev_t dev, struct uio *uiop, cred_t *cred_p)
3000 {
3001 #ifdef DEBUG
3002 	GET_SOFT_STATE(dev);
3003 	ST_ENTR(ST_DEVINFO, st_read);
3004 #endif
3005 	return (st_rw(dev, uiop, B_READ));
3006 }
3007 
3008 /* ARGSUSED */
3009 static int
3010 st_write(dev_t dev, struct uio *uiop, cred_t *cred_p)
3011 {
3012 #ifdef DEBUG
3013 	GET_SOFT_STATE(dev);
3014 	ST_ENTR(ST_DEVINFO, st_write);
3015 #endif
3016 	return (st_rw(dev, uiop, B_WRITE));
3017 }
3018 
3019 /*
3020  * Due to historical reasons, old limits are: For variable-length devices:
3021  * if greater than 64KB - 1 (ST_MAXRECSIZE_VARIABLE), block into 64 KB - 2
3022  * ST_MAXRECSIZE_VARIABLE_LIMIT) requests; otherwise,
3023  * (let it through unmodified. For fixed-length record devices:
3024  * 63K (ST_MAXRECSIZE_FIXED) is max (default minphys).
3025  *
3026  * The new limits used are un_maxdma (retrieved using scsi_ifgetcap()
3027  * from the HBA) and un_maxbsize (retrieved by sending SCMD_READ_BLKLIM
3028  * command to the drive).
3029  *
3030  */
3031 static void
3032 st_minphys(struct buf *bp)
3033 {
3034 	struct scsi_tape *un;
3035 
3036 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
3037 
3038 	ST_FUNC(ST_DEVINFO, st_minphys);
3039 
3040 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3041 	    "st_minphys(bp = 0x%p): b_bcount = 0x%lx\n", (void *)bp,
3042 	    bp->b_bcount);
3043 
3044 	if (un->un_allow_large_xfer) {
3045 
3046 		/*
3047 		 * check un_maxbsize for variable length devices only
3048 		 */
3049 		if (un->un_bsize == 0 && bp->b_bcount > un->un_maxbsize) {
3050 			bp->b_bcount = un->un_maxbsize;
3051 		}
3052 		/*
3053 		 * can't go more that HBA maxdma limit in either fixed-length
3054 		 * or variable-length tape drives.
3055 		 */
3056 		if (bp->b_bcount > un->un_maxdma) {
3057 			bp->b_bcount = un->un_maxdma;
3058 		}
3059 	} else {
3060 
3061 		/*
3062 		 *  use old fixed limits
3063 		 */
3064 		if (un->un_bsize == 0) {
3065 			if (bp->b_bcount > ST_MAXRECSIZE_VARIABLE) {
3066 				bp->b_bcount = ST_MAXRECSIZE_VARIABLE_LIMIT;
3067 			}
3068 		} else {
3069 			if (bp->b_bcount > ST_MAXRECSIZE_FIXED) {
3070 				bp->b_bcount = ST_MAXRECSIZE_FIXED;
3071 			}
3072 		}
3073 	}
3074 
3075 	/*
3076 	 * For regular raw I/O and Fixed Block length devices, make sure
3077 	 * the adjusted block count is a whole multiple of the device
3078 	 * block size.
3079 	 */
3080 	if (bp != un->un_sbufp && un->un_bsize) {
3081 		bp->b_bcount -= (bp->b_bcount % un->un_bsize);
3082 	}
3083 }
3084 
3085 static int
3086 st_rw(dev_t dev, struct uio *uio, int flag)
3087 {
3088 	int rval = 0;
3089 	long len;
3090 
3091 	GET_SOFT_STATE(dev);
3092 
3093 	ST_FUNC(ST_DEVINFO, st_rw);
3094 
3095 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3096 	    "st_rw(dev = 0x%lx, flag = %s)\n", dev,
3097 	    (flag == B_READ ? rd_str: wr_str));
3098 
3099 	/* get local copy of transfer length */
3100 	len = uio->uio_iov->iov_len;
3101 
3102 	mutex_enter(ST_MUTEX);
3103 
3104 	/*
3105 	 * If in fixed block size mode and requested read or write
3106 	 * is not an even multiple of that block size.
3107 	 */
3108 	if ((un->un_bsize != 0) && (len % un->un_bsize != 0)) {
3109 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
3110 		    "%s: not modulo %d block size\n",
3111 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_bsize);
3112 		rval = EINVAL;
3113 	}
3114 
3115 	/* If device has set granularity in the READ_BLKLIM we honor it. */
3116 	if ((un->un_data_mod != 0) && (len % un->un_data_mod != 0)) {
3117 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
3118 		    "%s: not modulo %d device granularity\n",
3119 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_data_mod);
3120 		rval = EINVAL;
3121 	}
3122 
3123 	if (rval != 0) {
3124 		un->un_errno = rval;
3125 		mutex_exit(ST_MUTEX);
3126 		return (rval);
3127 	}
3128 
3129 	/*
3130 	 * Reset this so it can be set if Berkeley and read over a filemark.
3131 	 */
3132 	un->un_silent_skip = 0;
3133 	mutex_exit(ST_MUTEX);
3134 
3135 	len = uio->uio_resid;
3136 
3137 	rval = physio(st_strategy, (struct buf *)NULL,
3138 	    dev, flag, st_minphys, uio);
3139 	/*
3140 	 * if we have hit logical EOT during this xfer and there is not a
3141 	 * full residue, then set eof back  to ST_EOM to make sure that
3142 	 * the user will see at least one zero write
3143 	 * after this short write
3144 	 */
3145 	mutex_enter(ST_MUTEX);
3146 	if (un->un_pos.eof > ST_NO_EOF) {
3147 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3148 		"eof=%d resid=%lx\n", un->un_pos.eof, uio->uio_resid);
3149 	}
3150 	if (un->un_pos.eof >= ST_EOM && (flag == B_WRITE)) {
3151 		if ((uio->uio_resid != len) && (uio->uio_resid != 0)) {
3152 			un->un_pos.eof = ST_EOM;
3153 		} else if (uio->uio_resid == len) {
3154 			un->un_pos.eof = ST_NO_EOF;
3155 		}
3156 	}
3157 
3158 	if (un->un_silent_skip && uio->uio_resid != len) {
3159 		un->un_pos.eof = ST_EOF;
3160 		un->un_pos.blkno = un->un_save_blkno;
3161 		un->un_pos.fileno--;
3162 	}
3163 
3164 	un->un_errno = rval;
3165 
3166 	mutex_exit(ST_MUTEX);
3167 
3168 	return (rval);
3169 }
3170 
3171 static int
3172 st_arw(dev_t dev, struct aio_req *aio, int flag)
3173 {
3174 	struct uio *uio = aio->aio_uio;
3175 	int rval = 0;
3176 	long len;
3177 
3178 	GET_SOFT_STATE(dev);
3179 
3180 	ST_FUNC(ST_DEVINFO, st_arw);
3181 
3182 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3183 	    "st_rw(dev = 0x%lx, flag = %s)\n", dev,
3184 	    (flag == B_READ ? rd_str: wr_str));
3185 
3186 	/* get local copy of transfer length */
3187 	len = uio->uio_iov->iov_len;
3188 
3189 	mutex_enter(ST_MUTEX);
3190 
3191 	/*
3192 	 * If in fixed block size mode and requested read or write
3193 	 * is not an even multiple of that block size.
3194 	 */
3195 	if ((un->un_bsize != 0) && (len % un->un_bsize != 0)) {
3196 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
3197 		    "%s: not modulo %d block size\n",
3198 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_bsize);
3199 		rval = EINVAL;
3200 	}
3201 
3202 	/* If device has set granularity in the READ_BLKLIM we honor it. */
3203 	if ((un->un_data_mod != 0) && (len % un->un_data_mod != 0)) {
3204 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
3205 		    "%s: not modulo %d device granularity\n",
3206 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_data_mod);
3207 		rval = EINVAL;
3208 	}
3209 
3210 	if (rval != 0) {
3211 		un->un_errno = rval;
3212 		mutex_exit(ST_MUTEX);
3213 		return (rval);
3214 	}
3215 
3216 	mutex_exit(ST_MUTEX);
3217 
3218 	len = uio->uio_resid;
3219 
3220 	rval = aphysio(st_strategy, anocancel, dev, flag, st_minphys, aio);
3221 
3222 	/*
3223 	 * if we have hit logical EOT during this xfer and there is not a
3224 	 * full residue, then set eof back  to ST_EOM to make sure that
3225 	 * the user will see at least one zero write
3226 	 * after this short write
3227 	 *
3228 	 * we keep this here just in case the application is not using
3229 	 * persistent errors
3230 	 */
3231 	mutex_enter(ST_MUTEX);
3232 	if (un->un_pos.eof > ST_NO_EOF) {
3233 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3234 		    "eof=%d resid=%lx\n", un->un_pos.eof, uio->uio_resid);
3235 	}
3236 	if (un->un_pos.eof >= ST_EOM && (flag == B_WRITE)) {
3237 		if ((uio->uio_resid != len) && (uio->uio_resid != 0)) {
3238 			un->un_pos.eof = ST_EOM;
3239 		} else if (uio->uio_resid == len && !IS_PE_FLAG_SET(un)) {
3240 			un->un_pos.eof = ST_NO_EOF;
3241 		}
3242 	}
3243 	un->un_errno = rval;
3244 	mutex_exit(ST_MUTEX);
3245 
3246 	return (rval);
3247 }
3248 
3249 
3250 
3251 static int
3252 st_strategy(struct buf *bp)
3253 {
3254 	struct scsi_tape *un;
3255 	dev_t dev = bp->b_edev;
3256 
3257 	/*
3258 	 * validate arguments
3259 	 */
3260 	if ((un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev))) == NULL) {
3261 		bp->b_resid = bp->b_bcount;
3262 		mutex_enter(ST_MUTEX);
3263 		st_bioerror(bp, ENXIO);
3264 		mutex_exit(ST_MUTEX);
3265 		goto error;
3266 	}
3267 
3268 	ST_ENTR(ST_DEVINFO, st_strategy);
3269 
3270 	mutex_enter(ST_MUTEX);
3271 
3272 	while (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
3273 		cv_wait(&un->un_suspend_cv, ST_MUTEX);
3274 	}
3275 
3276 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3277 	    "st_strategy(): bcount=0x%lx, fileno=%d, blkno=%x, eof=%d\n",
3278 	    bp->b_bcount, un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
3279 
3280 	/*
3281 	 * If persistent errors have been flagged, just nix this one. We wait
3282 	 * for any outstanding I/O's below, so we will be in order.
3283 	 */
3284 	if (IS_PE_FLAG_SET(un)) {
3285 		goto exit;
3286 	}
3287 
3288 	if (bp != un->un_sbufp) {
3289 		char reading = bp->b_flags & B_READ;
3290 		int wasopening = 0;
3291 
3292 		/*
3293 		 * If we haven't done/checked reservation on the tape unit
3294 		 * do it now.
3295 		 */
3296 		if ((un->un_rsvd_status &
3297 		    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
3298 			if ((un->un_dp->options & ST_NO_RESERVE_RELEASE) == 0) {
3299 				if (st_reserve_release(un, ST_RESERVE)) {
3300 					st_bioerror(bp, un->un_errno);
3301 					goto exit;
3302 				}
3303 			} else if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
3304 				/*
3305 				 * Enter here to restore position for possible
3306 				 * resets when the device was closed and opened
3307 				 * in O_NDELAY mode subsequently
3308 				 */
3309 				un->un_state = ST_STATE_INITIALIZING;
3310 				(void) st_cmd(dev, SCMD_TEST_UNIT_READY,
3311 				    0, SYNC_CMD);
3312 				un->un_state = ST_STATE_OPEN_PENDING_IO;
3313 			}
3314 			un->un_rsvd_status |= ST_INIT_RESERVE;
3315 		}
3316 
3317 		/*
3318 		 * If we are offline, we have to initialize everything first.
3319 		 * This is to handle either when opened with O_NDELAY, or
3320 		 * we just got a new tape in the drive, after an offline.
3321 		 * We don't observe O_NDELAY past the open,
3322 		 * as it will not make sense for tapes.
3323 		 */
3324 		if (un->un_state == ST_STATE_OFFLINE || un->un_restore_pos) {
3325 			/* reset state to avoid recursion */
3326 			un->un_state = ST_STATE_INITIALIZING;
3327 			if (st_tape_init(dev)) {
3328 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3329 				    "stioctl : OFFLINE init failure ");
3330 				un->un_state = ST_STATE_OFFLINE;
3331 				un->un_pos.pmode = invalid;
3332 				goto b_done_err;
3333 			}
3334 			un->un_state = ST_STATE_OPEN_PENDING_IO;
3335 		}
3336 		/*
3337 		 * Check for legal operations
3338 		 */
3339 		if (un->un_pos.pmode == invalid) {
3340 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3341 			    "strategy with un->un_pos.pmode invalid\n");
3342 			goto b_done_err;
3343 		}
3344 
3345 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3346 		    "st_strategy(): regular io\n");
3347 
3348 		/*
3349 		 * Process this first. If we were reading, and we're pending
3350 		 * logical eot, that means we've bumped one file mark too far.
3351 		 */
3352 
3353 		/*
3354 		 * Recursion warning: st_cmd will route back through here.
3355 		 */
3356 		if (un->un_pos.eof == ST_EOT_PENDING) {
3357 			if (st_cmd(dev, SCMD_SPACE, Fmk((-1)), SYNC_CMD)) {
3358 				un->un_pos.pmode = invalid;
3359 				un->un_density_known = 0;
3360 				goto b_done_err;
3361 			}
3362 			un->un_pos.blkno = 0; /* fix up block number.. */
3363 			un->un_pos.eof = ST_EOT;
3364 		}
3365 
3366 		/*
3367 		 * If we are in the process of opening, we may have to
3368 		 * determine/set the correct density. We also may have
3369 		 * to do a test_append (if QIC) to see whether we are
3370 		 * in a position to append to the end of the tape.
3371 		 *
3372 		 * If we're already at logical eot, we transition
3373 		 * to ST_NO_EOF. If we're at physical eot, we punt
3374 		 * to the switch statement below to handle.
3375 		 */
3376 		if ((un->un_state == ST_STATE_OPEN_PENDING_IO) ||
3377 		    (un->un_test_append && (un->un_dp->options & ST_QIC))) {
3378 
3379 			if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
3380 				if (st_determine_density(dev, (int)reading)) {
3381 					goto b_done_err;
3382 				}
3383 			}
3384 
3385 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3386 			    "pending_io@fileno %d rw %d qic %d eof %d\n",
3387 			    un->un_pos.fileno, (int)reading,
3388 			    (un->un_dp->options & ST_QIC) ? 1 : 0,
3389 			    un->un_pos.eof);
3390 
3391 			if (!reading && un->un_pos.eof != ST_EOM) {
3392 				if (un->un_pos.eof == ST_EOT) {
3393 					un->un_pos.eof = ST_NO_EOF;
3394 				} else if (un->un_pos.pmode != invalid &&
3395 				    (un->un_dp->options & ST_QIC)) {
3396 					/*
3397 					 * st_test_append() will do it all
3398 					 */
3399 					st_test_append(bp);
3400 					goto done;
3401 				}
3402 			}
3403 			if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
3404 				wasopening = 1;
3405 			}
3406 			un->un_laststate = un->un_state;
3407 			un->un_state = ST_STATE_OPEN;
3408 		}
3409 
3410 
3411 		/*
3412 		 * Process rest of END OF FILE and END OF TAPE conditions
3413 		 */
3414 
3415 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3416 		    "eof=%x, wasopening=%x\n",
3417 		    un->un_pos.eof, wasopening);
3418 
3419 		switch (un->un_pos.eof) {
3420 		case ST_EOM:
3421 			/*
3422 			 * This allows writes to proceed past physical
3423 			 * eot. We'll *really* be in trouble if the
3424 			 * user continues blindly writing data too
3425 			 * much past this point (unwind the tape).
3426 			 * Physical eot really means 'early warning
3427 			 * eot' in this context.
3428 			 *
3429 			 * Every other write from now on will succeed
3430 			 * (if sufficient  tape left).
3431 			 * This write will return with resid == count
3432 			 * but the next one should be successful
3433 			 *
3434 			 * Note that we only transition to logical EOT
3435 			 * if the last state wasn't the OPENING state.
3436 			 * We explicitly prohibit running up to physical
3437 			 * eot, closing the device, and then re-opening
3438 			 * to proceed. Trailer records may only be gotten
3439 			 * at by keeping the tape open after hitting eot.
3440 			 *
3441 			 * Also note that ST_EOM cannot be set by reading-
3442 			 * this can only be set during writing. Reading
3443 			 * up to the end of the tape gets a blank check
3444 			 * or a double-filemark indication (ST_EOT_PENDING),
3445 			 * and we prohibit reading after that point.
3446 			 *
3447 			 */
3448 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "EOM\n");
3449 			if (wasopening == 0) {
3450 				/*
3451 				 * this allows st_rw() to reset it back to
3452 				 * ST_EOM to make sure that the application
3453 				 * will see a zero write
3454 				 */
3455 				un->un_pos.eof = ST_WRITE_AFTER_EOM;
3456 			}
3457 			un->un_status = SUN_KEY_EOT;
3458 			goto b_done;
3459 
3460 		case ST_WRITE_AFTER_EOM:
3461 		case ST_EOT:
3462 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "EOT\n");
3463 			un->un_status = SUN_KEY_EOT;
3464 			if (SVR4_BEHAVIOR && reading) {
3465 				goto b_done_err;
3466 			}
3467 
3468 			if (reading) {
3469 				goto b_done;
3470 			}
3471 			un->un_pos.eof = ST_NO_EOF;
3472 			break;
3473 
3474 		case ST_EOF_PENDING:
3475 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3476 			    "EOF PENDING\n");
3477 			un->un_status = SUN_KEY_EOF;
3478 			if (SVR4_BEHAVIOR) {
3479 				un->un_pos.eof = ST_EOF;
3480 				goto b_done;
3481 			}
3482 			/* FALLTHROUGH */
3483 		case ST_EOF:
3484 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "EOF\n");
3485 			un->un_status = SUN_KEY_EOF;
3486 			if (SVR4_BEHAVIOR) {
3487 				goto b_done_err;
3488 			}
3489 
3490 			if (BSD_BEHAVIOR) {
3491 				un->un_pos.eof = ST_NO_EOF;
3492 				un->un_pos.fileno += 1;
3493 				un->un_pos.blkno   = 0;
3494 			}
3495 
3496 			if (reading) {
3497 				ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3498 				    "now file %d (read)\n",
3499 				    un->un_pos.fileno);
3500 				goto b_done;
3501 			}
3502 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3503 			    "now file %d (write)\n", un->un_pos.fileno);
3504 			break;
3505 		default:
3506 			un->un_status = 0;
3507 			break;
3508 		}
3509 	}
3510 
3511 	bp->b_flags &= ~(B_DONE);
3512 	st_bioerror(bp, 0);
3513 	bp->av_forw = NULL;
3514 	bp->b_resid = 0;
3515 	SET_BP_PKT(bp, 0);
3516 
3517 
3518 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3519 	    "st_strategy: cmd=0x%p  count=%ld  resid=%ld flags=0x%x"
3520 	    " pkt=0x%p\n",
3521 	    (void *)bp->b_forw, bp->b_bcount,
3522 	    bp->b_resid, bp->b_flags, (void *)BP_PKT(bp));
3523 
3524 #if defined(__i386) || defined(__amd64)
3525 	/*
3526 	 * We will replace bp with a new bp that can do big blk xfer
3527 	 * if the requested xfer size is bigger than ST_BIGBLK_XFER
3528 	 *
3529 	 * Also, we need to make sure that we're handling real I/O
3530 	 * by checking group 0/1 SCSI I/O commands, if needed
3531 	 */
3532 	if (bp->b_bcount > ST_BIGBLK_XFER &&
3533 	    (bp != un->un_sbufp					||
3534 	    (uchar_t)(uintptr_t)bp->b_forw == SCMD_READ		||
3535 	    (uchar_t)(uintptr_t)bp->b_forw == SCMD_READ_G1	||
3536 	    (uchar_t)(uintptr_t)bp->b_forw == SCMD_WRITE	||
3537 	    (uchar_t)(uintptr_t)bp->b_forw == SCMD_WRITE_G1)) {
3538 		mutex_exit(ST_MUTEX);
3539 		bp = st_get_bigblk_bp(bp);
3540 		mutex_enter(ST_MUTEX);
3541 	}
3542 #endif
3543 
3544 	/* put on wait queue */
3545 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3546 	    "st_strategy: un->un_quef = 0x%p, bp = 0x%p\n",
3547 	    (void *)un->un_quef, (void *)bp);
3548 
3549 	if (un->un_quef) {
3550 		un->un_quel->b_actf = bp;
3551 	} else {
3552 		un->un_quef = bp;
3553 	}
3554 	un->un_quel = bp;
3555 
3556 	ST_DO_KSTATS(bp, kstat_waitq_enter);
3557 
3558 	st_start(un);
3559 
3560 done:
3561 	mutex_exit(ST_MUTEX);
3562 	return (0);
3563 
3564 
3565 error:
3566 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3567 	    "st_strategy: error exit\n");
3568 
3569 	biodone(bp);
3570 	return (0);
3571 
3572 b_done_err:
3573 	st_bioerror(bp, EIO);
3574 	ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3575 	    "st_strategy : EIO b_done_err\n");
3576 
3577 b_done:
3578 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3579 	    "st_strategy: b_done\n");
3580 
3581 exit:
3582 	/*
3583 	 * make sure no commands are outstanding or waiting before closing,
3584 	 * so we can guarantee order
3585 	 */
3586 	st_wait_for_io(un);
3587 	un->un_err_resid = bp->b_resid = bp->b_bcount;
3588 
3589 	/* override errno here, if persistent errors were flagged */
3590 	if (IS_PE_FLAG_SET(un))
3591 		bioerror(bp, un->un_errno);
3592 
3593 	mutex_exit(ST_MUTEX);
3594 
3595 	biodone(bp);
3596 	ASSERT(mutex_owned(ST_MUTEX) == 0);
3597 	return (0);
3598 }
3599 
3600 
3601 
3602 /*
3603  * this routine spaces forward over filemarks
3604  */
3605 static int
3606 st_space_fmks(dev_t dev, int count)
3607 {
3608 	int rval = 0;
3609 
3610 	GET_SOFT_STATE(dev);
3611 
3612 	ST_FUNC(ST_DEVINFO, st_space_fmks);
3613 
3614 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3615 	    "st_space_fmks(dev = 0x%lx, count = %d)\n", dev, count);
3616 
3617 	ASSERT(mutex_owned(ST_MUTEX));
3618 
3619 	/*
3620 	 * the risk with doing only one space operation is that we
3621 	 * may accidentily jump in old data
3622 	 * the exabyte 8500 reading 8200 tapes cannot use KNOWS_EOD
3623 	 * because the 8200 does not append a marker; in order not to
3624 	 * sacrifice the fast file skip, we do a slow skip if the low
3625 	 * density device has been opened
3626 	 */
3627 
3628 	if ((un->un_dp->options & ST_KNOWS_EOD) &&
3629 	    !((un->un_dp->type == ST_TYPE_EXB8500 && MT_DENSITY(dev) == 0))) {
3630 		if (st_cmd(dev, SCMD_SPACE, Fmk(count), SYNC_CMD)) {
3631 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3632 			    "space_fmks : EIO can't do space cmd #1\n");
3633 			rval = EIO;
3634 		}
3635 	} else {
3636 		while (count > 0) {
3637 			if (st_cmd(dev, SCMD_SPACE, Fmk(1), SYNC_CMD)) {
3638 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3639 				    "space_fmks : EIO can't do space cmd #2\n");
3640 				rval = EIO;
3641 				break;
3642 			}
3643 			count -= 1;
3644 			/*
3645 			 * read a block to see if we have reached
3646 			 * end of medium (double filemark for reel or
3647 			 * medium error for others)
3648 			 */
3649 			if (count > 0) {
3650 				if (st_cmd(dev, SCMD_SPACE, Blk(1),
3651 				    SYNC_CMD)) {
3652 					ST_DEBUG2(ST_DEVINFO, st_label,
3653 					    SCSI_DEBUG,
3654 					    "space_fmks : EIO can't do "
3655 					    "space cmd #3\n");
3656 					rval = EIO;
3657 					break;
3658 				}
3659 				if ((un->un_pos.eof >= ST_EOF_PENDING) &&
3660 				    (un->un_dp->options & ST_REEL)) {
3661 					un->un_status = SUN_KEY_EOT;
3662 					ST_DEBUG2(ST_DEVINFO, st_label,
3663 					    SCSI_DEBUG,
3664 					    "space_fmks : EIO ST_REEL\n");
3665 					rval = EIO;
3666 					break;
3667 				} else if (IN_EOF(un->un_pos)) {
3668 					un->un_pos.eof = ST_NO_EOF;
3669 					un->un_pos.fileno++;
3670 					un->un_pos.blkno = 0;
3671 					count--;
3672 				} else if (un->un_pos.eof > ST_EOF) {
3673 					ST_DEBUG2(ST_DEVINFO, st_label,
3674 					    SCSI_DEBUG,
3675 					    "space_fmks, EIO > ST_EOF\n");
3676 					rval = EIO;
3677 					break;
3678 				}
3679 
3680 			}
3681 		}
3682 		un->un_err_resid = count;
3683 		COPY_POS(&un->un_pos, &un->un_err_pos);
3684 	}
3685 	ASSERT(mutex_owned(ST_MUTEX));
3686 	return (rval);
3687 }
3688 
3689 /*
3690  * this routine spaces to EOD
3691  *
3692  * it keeps track of the current filenumber and returns the filenumber after
3693  * the last successful space operation, we keep the number high because as
3694  * tapes are getting larger, the possibility of more and more files exist,
3695  * 0x100000 (1 Meg of files) probably will never have to be changed any time
3696  * soon
3697  */
3698 #define	MAX_SKIP	0x100000 /* somewhat arbitrary */
3699 
3700 static int
3701 st_find_eod(dev_t dev)
3702 {
3703 	tapepos_t savepos;
3704 	int sp_type;
3705 	struct scsi_tape *un;
3706 	int instance;
3707 	int result;
3708 
3709 	instance = MTUNIT(dev);
3710 	un = ddi_get_soft_state(st_state, instance);
3711 	if (un == NULL) {
3712 		return (-1);
3713 	}
3714 
3715 	ST_FUNC(ST_DEVINFO, st_find_eod);
3716 
3717 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3718 	    "st_find_eod(dev = 0x%lx): fileno = %d\n", dev, un->un_pos.fileno);
3719 
3720 	ASSERT(mutex_owned(ST_MUTEX));
3721 
3722 	COPY_POS(&savepos, &un->un_pos);
3723 
3724 	/*
3725 	 * see if the drive is smart enough to do the skips in
3726 	 * one operation; 1/2" use two filemarks
3727 	 * the exabyte 8500 reading 8200 tapes cannot use KNOWS_EOD
3728 	 * because the 8200 does not append a marker; in order not to
3729 	 * sacrifice the fast file skip, we do a slow skip if the low
3730 	 * density device has been opened
3731 	 */
3732 	if ((un->un_dp->options & ST_KNOWS_EOD) != 0) {
3733 		if ((un->un_dp->type == ST_TYPE_EXB8500) &&
3734 		    (MT_DENSITY(dev) == 0)) {
3735 			sp_type = Fmk(1);
3736 		} else if (un->un_pos.pmode == logical) {
3737 			sp_type = SPACE(SP_EOD, 0);
3738 		} else {
3739 			sp_type = Fmk(MAX_SKIP);
3740 		}
3741 	} else {
3742 		sp_type = Fmk(1);
3743 	}
3744 
3745 	for (;;) {
3746 		result = st_cmd(dev, SCMD_SPACE, sp_type, SYNC_CMD);
3747 
3748 		if (result == 0) {
3749 			COPY_POS(&savepos, &un->un_pos);
3750 		}
3751 
3752 		if (sp_type == SPACE(SP_EOD, 0)) {
3753 			if (result != 0) {
3754 				sp_type = Fmk(MAX_SKIP);
3755 				continue;
3756 			}
3757 
3758 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3759 			    "st_find_eod: 0x%"PRIx64"\n",
3760 			    savepos.lgclblkno);
3761 			/*
3762 			 * What we return will become the current file position.
3763 			 * After completing the space command with the position
3764 			 * mode that is not invalid a read position command will
3765 			 * be automaticly issued. If the drive support the long
3766 			 * read position format a valid file position can be
3767 			 * returned.
3768 			 */
3769 			return (un->un_pos.fileno);
3770 		}
3771 
3772 		if (result != 0) {
3773 			break;
3774 		}
3775 
3776 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3777 		    "count=%x, eof=%x, status=%x\n",
3778 		    SPACE_CNT(sp_type),  un->un_pos.eof, un->un_status);
3779 
3780 		/*
3781 		 * If we're not EOM smart,  space a record
3782 		 * to see whether we're now in the slot between
3783 		 * the two sequential filemarks that logical
3784 		 * EOM consists of (REEL) or hit nowhere land
3785 		 * (8mm).
3786 		 */
3787 		if (sp_type == Fmk(1)) {
3788 			/*
3789 			 * no fast skipping, check a record
3790 			 */
3791 			if (st_cmd(dev, SCMD_SPACE, Blk((1)), SYNC_CMD)) {
3792 				break;
3793 			}
3794 			if ((un->un_pos.eof >= ST_EOF_PENDING) &&
3795 			    (un->un_dp->options & ST_REEL)) {
3796 				un->un_status = KEY_BLANK_CHECK;
3797 				un->un_pos.fileno++;
3798 				un->un_pos.blkno = 0;
3799 				break;
3800 			}
3801 			if (IN_EOF(un->un_pos)) {
3802 				un->un_pos.eof = ST_NO_EOF;
3803 				un->un_pos.fileno++;
3804 				un->un_pos.blkno = 0;
3805 			}
3806 			if (un->un_pos.eof > ST_EOF) {
3807 				break;
3808 			}
3809 		} else {
3810 			if (un->un_pos.eof > ST_EOF) {
3811 				break;
3812 			}
3813 		}
3814 	}
3815 
3816 	if (un->un_dp->options & ST_KNOWS_EOD) {
3817 		COPY_POS(&savepos, &un->un_pos);
3818 	}
3819 
3820 	ASSERT(mutex_owned(ST_MUTEX));
3821 
3822 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3823 	    "st_find_eod: %x\n", savepos.fileno);
3824 	return (savepos.fileno);
3825 }
3826 
3827 
3828 /*
3829  * this routine is frequently used in ioctls below;
3830  * it determines whether we know the density and if not will
3831  * determine it
3832  * if we have written the tape before, one or more filemarks are written
3833  *
3834  * depending on the stepflag, the head is repositioned to where it was before
3835  * the filemarks were written in order not to confuse step counts
3836  */
3837 #define	STEPBACK    0
3838 #define	NO_STEPBACK 1
3839 
3840 static int
3841 st_check_density_or_wfm(dev_t dev, int wfm, int mode, int stepflag)
3842 {
3843 
3844 	GET_SOFT_STATE(dev);
3845 
3846 	ST_FUNC(ST_DEVINFO, st_check_density_or_wfm);
3847 
3848 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3849 	    "st_check_density_or_wfm(dev= 0x%lx, wfm= %d, mode= %d, stpflg= %d)"
3850 	    "\n", dev, wfm, mode, stepflag);
3851 
3852 	ASSERT(mutex_owned(ST_MUTEX));
3853 
3854 	/*
3855 	 * If we don't yet know the density of the tape we have inserted,
3856 	 * we have to either unconditionally set it (if we're 'writing'),
3857 	 * or we have to determine it. As side effects, check for any
3858 	 * write-protect errors, and for the need to put out any file-marks
3859 	 * before positioning a tape.
3860 	 *
3861 	 * If we are going to be spacing forward, and we haven't determined
3862 	 * the tape density yet, we have to do so now...
3863 	 */
3864 	if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
3865 		if (st_determine_density(dev, mode)) {
3866 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3867 			    "check_density_or_wfm : EIO can't determine "
3868 			    "density\n");
3869 			un->un_errno = EIO;
3870 			return (EIO);
3871 		}
3872 		/*
3873 		 * Presumably we are at BOT. If we attempt to write, it will
3874 		 * either work okay, or bomb. We don't do a st_test_append
3875 		 * unless we're past BOT.
3876 		 */
3877 		un->un_laststate = un->un_state;
3878 		un->un_state = ST_STATE_OPEN;
3879 
3880 	} else if (un->un_pos.pmode != invalid && un->un_fmneeded > 0 &&
3881 	    ((un->un_lastop == ST_OP_WEOF && wfm) ||
3882 	    (un->un_lastop == ST_OP_WRITE && wfm))) {
3883 
3884 		tapepos_t spos;
3885 
3886 		COPY_POS(&spos, &un->un_pos);
3887 
3888 		/*
3889 		 * We need to write one or two filemarks.
3890 		 * In the case of the HP, we need to
3891 		 * position the head between the two
3892 		 * marks.
3893 		 */
3894 		if ((un->un_fmneeded > 0) || (un->un_lastop == ST_OP_WEOF)) {
3895 			wfm = un->un_fmneeded;
3896 			un->un_fmneeded = 0;
3897 		}
3898 
3899 		if (st_write_fm(dev, wfm)) {
3900 			un->un_pos.pmode = invalid;
3901 			un->un_density_known = 0;
3902 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3903 			    "check_density_or_wfm : EIO can't write fm\n");
3904 			un->un_errno = EIO;
3905 			return (EIO);
3906 		}
3907 
3908 		if (stepflag == STEPBACK) {
3909 			if (st_cmd(dev, SCMD_SPACE, Fmk((-wfm)), SYNC_CMD)) {
3910 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3911 				    "check_density_or_wfm : EIO can't space "
3912 				    "(-wfm)\n");
3913 				un->un_errno = EIO;
3914 				return (EIO);
3915 			}
3916 			COPY_POS(&un->un_pos, &spos);
3917 		}
3918 	}
3919 
3920 	/*
3921 	 * Whatever we do at this point clears the state of the eof flag.
3922 	 */
3923 
3924 	un->un_pos.eof = ST_NO_EOF;
3925 
3926 	/*
3927 	 * If writing, let's check that we're positioned correctly
3928 	 * at the end of tape before issuing the next write.
3929 	 */
3930 	if (un->un_read_only == RDWR) {
3931 		un->un_test_append = 1;
3932 	}
3933 
3934 	ASSERT(mutex_owned(ST_MUTEX));
3935 	return (0);
3936 }
3937 
3938 
3939 /*
3940  * Wait for all outstaning I/O's to complete
3941  *
3942  * we wait on both ncmds and the wait queue for times when we are flushing
3943  * after persistent errors are flagged, which is when ncmds can be 0, and the
3944  * queue can still have I/O's.  This way we preserve order of biodone's.
3945  */
3946 static void
3947 st_wait_for_io(struct scsi_tape *un)
3948 {
3949 	ST_FUNC(ST_DEVINFO, st_wait_for_io);
3950 	ASSERT(mutex_owned(ST_MUTEX));
3951 	while (un->un_ncmds && un->un_quef) { /* XXX fix for async write@EOM */
3952 		cv_wait(&un->un_queue_cv, ST_MUTEX);
3953 	}
3954 }
3955 
3956 /*
3957  * This routine implements the ioctl calls.  It is called
3958  * from the device switch at normal priority.
3959  */
3960 /*ARGSUSED*/
3961 static int
3962 st_ioctl(dev_t dev, int cmd, intptr_t arg, int flag, cred_t *cred_p,
3963     int *rval_p)
3964 {
3965 	int tmp, rval = 0;
3966 
3967 	GET_SOFT_STATE(dev);
3968 
3969 	ST_ENTR(ST_DEVINFO, st_ioctl);
3970 
3971 	mutex_enter(ST_MUTEX);
3972 
3973 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3974 	    "st_ioctl(): fileno=%x, blkno=%x, eof=%x, state = %d, "
3975 	    "pe_flag = %d\n",
3976 	    un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof, un->un_state,
3977 	    IS_PE_FLAG_SET(un));
3978 
3979 	/*
3980 	 * We don't want to block on these, so let them through
3981 	 * and we don't care about setting driver states here.
3982 	 */
3983 	if ((cmd == MTIOCGETDRIVETYPE) ||
3984 	    (cmd == MTIOCGUARANTEEDORDER) ||
3985 	    (cmd == MTIOCPERSISTENTSTATUS)) {
3986 		goto check_commands;
3987 	}
3988 
3989 	/*
3990 	 * wait for all outstanding commands to complete, or be dequeued.
3991 	 * And because ioctl's are synchronous commands, any return value
3992 	 * after this,  will be in order
3993 	 */
3994 	st_wait_for_io(un);
3995 
3996 	/*
3997 	 * allow only a through clear errors and persistent status, and
3998 	 * status
3999 	 */
4000 	if (IS_PE_FLAG_SET(un)) {
4001 		if ((cmd == MTIOCLRERR) ||
4002 		    (cmd == MTIOCPERSISTENT) ||
4003 		    (cmd == MTIOCGET)) {
4004 			goto check_commands;
4005 		} else {
4006 			rval = un->un_errno;
4007 			goto exit;
4008 		}
4009 	}
4010 
4011 	un->un_throttle = 1;	/* > 1 will never happen here */
4012 	un->un_errno = 0;	/* start clean from here */
4013 
4014 	/*
4015 	 * first and foremost, handle any ST_EOT_PENDING cases.
4016 	 * That is, if a logical eot is pending notice, notice it.
4017 	 */
4018 	if (un->un_pos.eof == ST_EOT_PENDING) {
4019 		int resid = un->un_err_resid;
4020 		uchar_t status = un->un_status;
4021 		uchar_t lastop = un->un_lastop;
4022 
4023 		if (st_cmd(dev, SCMD_SPACE, Fmk((-1)), SYNC_CMD)) {
4024 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4025 			    "stioctl : EIO can't space fmk(-1)\n");
4026 			rval = EIO;
4027 			goto exit;
4028 		}
4029 		un->un_lastop = lastop; /* restore last operation */
4030 		if (status == SUN_KEY_EOF) {
4031 			un->un_status = SUN_KEY_EOT;
4032 		} else {
4033 			un->un_status = status;
4034 		}
4035 		un->un_err_resid  = resid;
4036 		/* fix up block number */
4037 		un->un_err_pos.blkno = un->un_pos.blkno = 0;
4038 		/* now we're at logical eot */
4039 		un->un_pos.eof = ST_EOT;
4040 	}
4041 
4042 	/*
4043 	 * now, handle the rest of the situations
4044 	 */
4045 check_commands:
4046 	switch (cmd) {
4047 	case MTIOCGET:
4048 	{
4049 #ifdef _MULTI_DATAMODEL
4050 		/*
4051 		 * For use when a 32 bit app makes a call into a
4052 		 * 64 bit ioctl
4053 		 */
4054 		struct mtget32		mtg_local32;
4055 		struct mtget32 		*mtget_32 = &mtg_local32;
4056 #endif /* _MULTI_DATAMODEL */
4057 
4058 			/* Get tape status */
4059 		struct mtget mtg_local;
4060 		struct mtget *mtget = &mtg_local;
4061 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4062 		    "st_ioctl: MTIOCGET\n");
4063 
4064 		bzero((caddr_t)mtget, sizeof (struct mtget));
4065 		mtget->mt_erreg = un->un_status;
4066 		mtget->mt_resid = un->un_err_resid;
4067 		mtget->mt_dsreg = un->un_retry_ct;
4068 		if (un->un_err_pos.pmode == legacy) {
4069 			mtget->mt_fileno = un->un_err_pos.fileno;
4070 		} else {
4071 			mtget->mt_fileno = -1;
4072 		}
4073 		mtget->mt_blkno = un->un_err_pos.blkno;
4074 		mtget->mt_type = un->un_dp->type;
4075 		mtget->mt_flags = MTF_SCSI | MTF_ASF;
4076 		if (un->un_read_pos_type != NO_POS) {
4077 			mtget->mt_flags |= MTF_LOGICAL_BLOCK;
4078 		}
4079 		if (un->un_dp->options & ST_REEL) {
4080 			mtget->mt_flags |= MTF_REEL;
4081 			mtget->mt_bf = 20;
4082 		} else {		/* 1/4" cartridges */
4083 			switch (mtget->mt_type) {
4084 			/* Emulex cartridge tape */
4085 			case MT_ISMT02:
4086 				mtget->mt_bf = 40;
4087 				break;
4088 			default:
4089 				mtget->mt_bf = 126;
4090 				break;
4091 			}
4092 		}
4093 
4094 		/*
4095 		 * If large transfers are allowed and drive options
4096 		 * has no record size limit set. Calculate blocking
4097 		 * factor from the lesser of maxbsize and maxdma.
4098 		 */
4099 		if ((un->un_allow_large_xfer) &&
4100 		    (un->un_dp->options & ST_NO_RECSIZE_LIMIT)) {
4101 			mtget->mt_bf = min(un->un_maxbsize,
4102 			    un->un_maxdma) / SECSIZE;
4103 		}
4104 
4105 			if (un->un_read_only == WORM ||
4106 			    un->un_read_only == RDWORM) {
4107 				mtget->mt_flags |= MTF_WORM_MEDIA;
4108 			}
4109 
4110 			rval = st_check_clean_bit(dev);
4111 			if (rval == -1) {
4112 				rval = EIO;
4113 				goto exit;
4114 			} else {
4115 				mtget->mt_flags |= (ushort_t)rval;
4116 				rval = 0;
4117 			}
4118 
4119 		un->un_status = 0;		/* Reset status */
4120 		un->un_err_resid = 0;
4121 		tmp = sizeof (struct mtget);
4122 
4123 #ifdef _MULTI_DATAMODEL
4124 
4125 		switch (ddi_model_convert_from(flag & FMODELS)) {
4126 		case DDI_MODEL_ILP32:
4127 			/*
4128 			 * Convert 64 bit back to 32 bit before doing
4129 			 * copyout. This is what the ILP32 app expects.
4130 			 */
4131 			mtget_32->mt_erreg = 	mtget->mt_erreg;
4132 			mtget_32->mt_resid = 	mtget->mt_resid;
4133 			mtget_32->mt_dsreg = 	mtget->mt_dsreg;
4134 			mtget_32->mt_fileno = 	(daddr32_t)mtget->mt_fileno;
4135 			mtget_32->mt_blkno = 	(daddr32_t)mtget->mt_blkno;
4136 			mtget_32->mt_type =  	mtget->mt_type;
4137 			mtget_32->mt_flags = 	mtget->mt_flags;
4138 			mtget_32->mt_bf = 	mtget->mt_bf;
4139 
4140 			if (ddi_copyout(mtget_32, (void *)arg,
4141 			    sizeof (struct mtget32), flag)) {
4142 				rval = EFAULT;
4143 			}
4144 			break;
4145 
4146 		case DDI_MODEL_NONE:
4147 			if (ddi_copyout(mtget, (void *)arg, tmp, flag)) {
4148 				rval = EFAULT;
4149 			}
4150 			break;
4151 		}
4152 #else /* ! _MULTI_DATAMODE */
4153 		if (ddi_copyout(mtget, (void *)arg, tmp, flag)) {
4154 			rval = EFAULT;
4155 		}
4156 #endif /* _MULTI_DATAMODE */
4157 
4158 		break;
4159 	}
4160 	case MTIOCSTATE:
4161 		{
4162 			/*
4163 			 * return when media presence matches state
4164 			 */
4165 			enum mtio_state state;
4166 
4167 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4168 			    "st_ioctl: MTIOCSTATE\n");
4169 
4170 			if (ddi_copyin((void *)arg, &state, sizeof (int), flag))
4171 				rval = EFAULT;
4172 
4173 			mutex_exit(ST_MUTEX);
4174 
4175 			rval = st_check_media(dev, state);
4176 
4177 			mutex_enter(ST_MUTEX);
4178 
4179 			if (rval != 0) {
4180 				break;
4181 			}
4182 
4183 			if (ddi_copyout(&un->un_mediastate, (void *)arg,
4184 			    sizeof (int), flag))
4185 				rval = EFAULT;
4186 			break;
4187 
4188 		}
4189 
4190 	case MTIOCGETDRIVETYPE:
4191 		{
4192 #ifdef _MULTI_DATAMODEL
4193 		/*
4194 		 * For use when a 32 bit app makes a call into a
4195 		 * 64 bit ioctl
4196 		 */
4197 		struct mtdrivetype_request32	mtdtrq32;
4198 #endif /* _MULTI_DATAMODEL */
4199 
4200 			/*
4201 			 * return mtdrivetype
4202 			 */
4203 			struct mtdrivetype_request mtdtrq;
4204 			struct mtdrivetype mtdrtyp;
4205 			struct mtdrivetype *mtdt = &mtdrtyp;
4206 			struct st_drivetype *stdt = un->un_dp;
4207 
4208 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4209 			    "st_ioctl: MTIOCGETDRIVETYPE\n");
4210 
4211 #ifdef _MULTI_DATAMODEL
4212 		switch (ddi_model_convert_from(flag & FMODELS)) {
4213 		case DDI_MODEL_ILP32:
4214 		{
4215 			if (ddi_copyin((void *)arg, &mtdtrq32,
4216 			    sizeof (struct mtdrivetype_request32), flag)) {
4217 				rval = EFAULT;
4218 				break;
4219 			}
4220 			mtdtrq.size = mtdtrq32.size;
4221 			mtdtrq.mtdtp =
4222 			    (struct  mtdrivetype *)(uintptr_t)mtdtrq32.mtdtp;
4223 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4224 			    "st_ioctl: size 0x%x\n", mtdtrq.size);
4225 			break;
4226 		}
4227 		case DDI_MODEL_NONE:
4228 			if (ddi_copyin((void *)arg, &mtdtrq,
4229 			    sizeof (struct mtdrivetype_request), flag)) {
4230 				rval = EFAULT;
4231 				break;
4232 			}
4233 			break;
4234 		}
4235 
4236 #else /* ! _MULTI_DATAMODEL */
4237 		if (ddi_copyin((void *)arg, &mtdtrq,
4238 		    sizeof (struct mtdrivetype_request), flag)) {
4239 			rval = EFAULT;
4240 			break;
4241 		}
4242 #endif /* _MULTI_DATAMODEL */
4243 
4244 			/*
4245 			 * if requested size is < 0 then return
4246 			 * error.
4247 			 */
4248 			if (mtdtrq.size < 0) {
4249 				rval = EINVAL;
4250 				break;
4251 			}
4252 			bzero(mtdt, sizeof (struct mtdrivetype));
4253 			(void) strncpy(mtdt->name, stdt->name, ST_NAMESIZE);
4254 			(void) strncpy(mtdt->vid, stdt->vid, VIDPIDLEN - 1);
4255 			mtdt->type = stdt->type;
4256 			mtdt->bsize = stdt->bsize;
4257 			mtdt->options = stdt->options;
4258 			mtdt->max_rretries = stdt->max_rretries;
4259 			mtdt->max_wretries = stdt->max_wretries;
4260 			for (tmp = 0; tmp < NDENSITIES; tmp++) {
4261 				mtdt->densities[tmp] = stdt->densities[tmp];
4262 			}
4263 			mtdt->default_density = stdt->default_density;
4264 			/*
4265 			 * Speed hasn't been used since the hayday of reel tape.
4266 			 * For all drives not setting the option ST_KNOWS_MEDIA
4267 			 * the speed member renamed to mediatype are zeros.
4268 			 * Those drives that have ST_KNOWS_MEDIA set use the
4269 			 * new mediatype member which is used to figure the
4270 			 * type of media loaded.
4271 			 *
4272 			 * So as to not break applications speed in the
4273 			 * mtdrivetype structure is not renamed.
4274 			 */
4275 			for (tmp = 0; tmp < NDENSITIES; tmp++) {
4276 				mtdt->speeds[tmp] = stdt->mediatype[tmp];
4277 			}
4278 			mtdt->non_motion_timeout = stdt->non_motion_timeout;
4279 			mtdt->io_timeout = stdt->io_timeout;
4280 			mtdt->rewind_timeout = stdt->rewind_timeout;
4281 			mtdt->space_timeout = stdt->space_timeout;
4282 			mtdt->load_timeout = stdt->load_timeout;
4283 			mtdt->unload_timeout = stdt->unload_timeout;
4284 			mtdt->erase_timeout = stdt->erase_timeout;
4285 
4286 			/*
4287 			 * Limit the maximum length of the result to
4288 			 * sizeof (struct mtdrivetype).
4289 			 */
4290 			tmp = sizeof (struct mtdrivetype);
4291 			if (mtdtrq.size < tmp)
4292 				tmp = mtdtrq.size;
4293 			if (ddi_copyout(mtdt, mtdtrq.mtdtp, tmp, flag)) {
4294 				rval = EFAULT;
4295 			}
4296 			break;
4297 		}
4298 	case MTIOCPERSISTENT:
4299 		{
4300 			int persistence = 0;
4301 
4302 			if (ddi_copyin((void *)arg, &persistence,
4303 			    sizeof (int), flag)) {
4304 				rval = EFAULT;
4305 				break;
4306 			}
4307 
4308 			/* non zero sets it, only 0 turns it off */
4309 			un->un_persistence = (uchar_t)persistence ? 1 : 0;
4310 
4311 			if (un->un_persistence) {
4312 				TURN_PE_ON(un);
4313 			} else {
4314 				TURN_PE_OFF(un);
4315 			}
4316 
4317 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4318 			    "st_ioctl: MTIOCPERSISTENT : persistence = %d\n",
4319 			    un->un_persistence);
4320 
4321 			break;
4322 		}
4323 	case MTIOCPERSISTENTSTATUS:
4324 		{
4325 			int persistence = (int)un->un_persistence;
4326 
4327 			if (ddi_copyout(&persistence, (void *)arg,
4328 			    sizeof (int), flag)) {
4329 				rval = EFAULT;
4330 			}
4331 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4332 			    "st_ioctl: MTIOCPERSISTENTSTATUS:persistece = %d\n",
4333 			    un->un_persistence);
4334 
4335 			break;
4336 		}
4337 
4338 
4339 	case MTIOCLRERR:
4340 		{
4341 			/* clear persistent errors */
4342 
4343 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4344 			    "st_ioctl: MTIOCLRERR\n");
4345 
4346 			CLEAR_PE(un);
4347 
4348 			break;
4349 		}
4350 
4351 	case MTIOCGUARANTEEDORDER:
4352 		{
4353 			/*
4354 			 * this is just a holder to make a valid ioctl and
4355 			 * it won't be in any earlier release
4356 			 */
4357 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4358 			    "st_ioctl: MTIOCGUARANTEEDORDER\n");
4359 
4360 			break;
4361 		}
4362 
4363 	case MTIOCRESERVE:
4364 		{
4365 			ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4366 			    "st_ioctl: MTIOCRESERVE\n");
4367 
4368 			/*
4369 			 * Check if Reserve/Release is supported.
4370 			 */
4371 			if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
4372 				rval = ENOTTY;
4373 				break;
4374 			}
4375 
4376 			rval = st_reserve_release(un, ST_RESERVE);
4377 
4378 			if (rval == 0) {
4379 				un->un_rsvd_status |= ST_PRESERVE_RESERVE;
4380 			}
4381 			break;
4382 		}
4383 
4384 	case MTIOCRELEASE:
4385 		{
4386 			ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4387 			    "st_ioctl: MTIOCRELEASE\n");
4388 
4389 			/*
4390 			 * Check if Reserve/Release is supported.
4391 			 */
4392 			if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
4393 				rval = ENOTTY;
4394 				break;
4395 			}
4396 
4397 			/*
4398 			 * Used to just clear ST_PRESERVE_RESERVE which
4399 			 * made the reservation release at next close.
4400 			 * As the user may have opened and then done a
4401 			 * persistant reservation we now need to drop
4402 			 * the reservation without closing if the user
4403 			 * attempts to do this.
4404 			 */
4405 			rval = st_reserve_release(un, ST_RELEASE);
4406 
4407 			un->un_rsvd_status &= ~ST_PRESERVE_RESERVE;
4408 
4409 			break;
4410 		}
4411 
4412 	case MTIOCFORCERESERVE:
4413 		{
4414 			ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4415 			    "st_ioctl: MTIOCFORCERESERVE\n");
4416 
4417 			/*
4418 			 * Check if Reserve/Release is supported.
4419 			 */
4420 			if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
4421 				rval = ENOTTY;
4422 				break;
4423 			}
4424 			/*
4425 			 * allow only super user to run this.
4426 			 */
4427 			if (drv_priv(cred_p) != 0) {
4428 				rval = EPERM;
4429 				break;
4430 			}
4431 			/*
4432 			 * Throw away reserve,
4433 			 * not using test-unit-ready
4434 			 * since reserve can succeed without tape being
4435 			 * present in the drive.
4436 			 */
4437 			(void) st_reserve_release(un, ST_RESERVE);
4438 
4439 			rval = st_take_ownership(dev);
4440 
4441 			break;
4442 		}
4443 
4444 	case USCSICMD:
4445 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4446 		    "st_ioctl: USCSICMD\n");
4447 	{
4448 		cred_t	*cr;
4449 		cr = ddi_get_cred();
4450 		if ((drv_priv(cred_p) != 0) && (drv_priv(cr) != 0)) {
4451 			rval = EPERM;
4452 		} else {
4453 			rval = st_ioctl_cmd(dev, (struct uscsi_cmd *)arg,
4454 			    flag);
4455 		}
4456 	}
4457 		break;
4458 
4459 	case MTIOCTOP:
4460 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4461 		    "st_ioctl: MTIOCTOP\n");
4462 		rval = st_mtioctop(un, arg, flag);
4463 		break;
4464 
4465 	case MTIOCLTOP:
4466 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4467 		    "st_ioctl: MTIOLCTOP\n");
4468 		rval = st_mtiocltop(un, arg, flag);
4469 		break;
4470 
4471 	case MTIOCREADIGNOREILI:
4472 		{
4473 			int set_ili;
4474 
4475 			if (ddi_copyin((void *)arg, &set_ili,
4476 			    sizeof (set_ili), flag)) {
4477 				rval = EFAULT;
4478 				break;
4479 			}
4480 
4481 			if (un->un_bsize) {
4482 				rval = ENOTTY;
4483 				break;
4484 			}
4485 
4486 			switch (set_ili) {
4487 			case 0:
4488 				un->un_dp->options &= ~ST_READ_IGNORE_ILI;
4489 				break;
4490 
4491 			case 1:
4492 				un->un_dp->options |= ST_READ_IGNORE_ILI;
4493 				break;
4494 
4495 			default:
4496 				rval = EINVAL;
4497 				break;
4498 			}
4499 			break;
4500 		}
4501 
4502 	case MTIOCREADIGNOREEOFS:
4503 		{
4504 			int ignore_eof;
4505 
4506 			if (ddi_copyin((void *)arg, &ignore_eof,
4507 			    sizeof (ignore_eof), flag)) {
4508 				rval = EFAULT;
4509 				break;
4510 			}
4511 
4512 			if (!(un->un_dp->options & ST_REEL)) {
4513 				rval = ENOTTY;
4514 				break;
4515 			}
4516 
4517 			switch (ignore_eof) {
4518 			case 0:
4519 				un->un_dp->options &= ~ST_READ_IGNORE_EOFS;
4520 				break;
4521 
4522 			case 1:
4523 				un->un_dp->options |= ST_READ_IGNORE_EOFS;
4524 				break;
4525 
4526 			default:
4527 				rval = EINVAL;
4528 				break;
4529 			}
4530 			break;
4531 		}
4532 
4533 	case MTIOCSHORTFMK:
4534 	{
4535 		int short_fmk;
4536 
4537 		if (ddi_copyin((void *)arg, &short_fmk,
4538 		    sizeof (short_fmk), flag)) {
4539 			rval = EFAULT;
4540 			break;
4541 		}
4542 
4543 		switch (un->un_dp->type) {
4544 		case ST_TYPE_EXB8500:
4545 		case ST_TYPE_EXABYTE:
4546 			if (!short_fmk) {
4547 				un->un_dp->options &= ~ST_SHORT_FILEMARKS;
4548 			} else if (short_fmk == 1) {
4549 				un->un_dp->options |= ST_SHORT_FILEMARKS;
4550 			} else {
4551 				rval = EINVAL;
4552 			}
4553 			break;
4554 
4555 		default:
4556 			rval = ENOTTY;
4557 			break;
4558 		}
4559 		break;
4560 	}
4561 
4562 	case MTIOCGETPOS:
4563 		rval = st_update_block_pos(un);
4564 		if (rval == 0) {
4565 			if (ddi_copyout((void *)&un->un_pos, (void *)arg,
4566 			    sizeof (tapepos_t), flag)) {
4567 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
4568 				    "MTIOCGETPOS copy out failed\n");
4569 				rval = EFAULT;
4570 			}
4571 		}
4572 		break;
4573 
4574 	case MTIOCRESTPOS:
4575 	{
4576 		tapepos_t dest;
4577 
4578 		if (ddi_copyin((void *)arg, &dest, sizeof (tapepos_t),
4579 		    flag) != 0) {
4580 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
4581 			    "MTIOCRESTPOS copy in failed\n");
4582 			rval = EFAULT;
4583 			break;
4584 		}
4585 		rval = st_validate_tapemarks(un, &dest);
4586 		if (rval != 0) {
4587 			rval = EIO;
4588 		}
4589 		break;
4590 	}
4591 	default:
4592 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4593 		    "st_ioctl: unknown ioctl\n");
4594 		rval = ENOTTY;
4595 	}
4596 
4597 exit:
4598 	if (!IS_PE_FLAG_SET(un)) {
4599 		un->un_errno = rval;
4600 	}
4601 
4602 	mutex_exit(ST_MUTEX);
4603 
4604 	return (rval);
4605 }
4606 
4607 
4608 /*
4609  * do some MTIOCTOP tape operations
4610  */
4611 static int
4612 st_mtioctop(struct scsi_tape *un, intptr_t arg, int flag)
4613 {
4614 #ifdef _MULTI_DATAMODEL
4615 	/*
4616 	 * For use when a 32 bit app makes a call into a
4617 	 * 64 bit ioctl
4618 	 */
4619 	struct mtop32	mtop_32_for_64;
4620 #endif /* _MULTI_DATAMODEL */
4621 	struct mtop passed;
4622 	struct mtlop local;
4623 	int rval = 0;
4624 
4625 	ST_FUNC(ST_DEVINFO, st_mtioctop);
4626 
4627 	ASSERT(mutex_owned(ST_MUTEX));
4628 
4629 #ifdef _MULTI_DATAMODEL
4630 	switch (ddi_model_convert_from(flag & FMODELS)) {
4631 	case DDI_MODEL_ILP32:
4632 		if (ddi_copyin((void *)arg, &mtop_32_for_64,
4633 		    sizeof (struct mtop32), flag)) {
4634 			return (EFAULT);
4635 		}
4636 		local.mt_op = mtop_32_for_64.mt_op;
4637 		local.mt_count =  (int64_t)mtop_32_for_64.mt_count;
4638 		break;
4639 
4640 	case DDI_MODEL_NONE:
4641 		if (ddi_copyin((void *)arg, &passed, sizeof (passed), flag)) {
4642 			return (EFAULT);
4643 		}
4644 		local.mt_op = passed.mt_op;
4645 		/* prevent sign extention */
4646 		local.mt_count = (UINT32_MAX & passed.mt_count);
4647 		break;
4648 	}
4649 
4650 #else /* ! _MULTI_DATAMODEL */
4651 	if (ddi_copyin((void *)arg, &passed, sizeof (passed), flag)) {
4652 		return (EFAULT);
4653 	}
4654 	local.mt_op = passed.mt_op;
4655 	/* prevent sign extention */
4656 	local.mt_count = (UINT32_MAX & passed.mt_count);
4657 #endif /* _MULTI_DATAMODEL */
4658 
4659 	rval = st_do_mtioctop(un, &local);
4660 
4661 #ifdef _MULTI_DATAMODEL
4662 	switch (ddi_model_convert_from(flag & FMODELS)) {
4663 	case DDI_MODEL_ILP32:
4664 		if (((uint64_t)local.mt_count) > UINT32_MAX) {
4665 			rval = ERANGE;
4666 			break;
4667 		}
4668 		/*
4669 		 * Convert 64 bit back to 32 bit before doing
4670 		 * copyout. This is what the ILP32 app expects.
4671 		 */
4672 		mtop_32_for_64.mt_op = local.mt_op;
4673 		mtop_32_for_64.mt_count = local.mt_count;
4674 
4675 		if (ddi_copyout(&mtop_32_for_64, (void *)arg,
4676 		    sizeof (struct mtop32), flag)) {
4677 			rval = EFAULT;
4678 		}
4679 		break;
4680 
4681 	case DDI_MODEL_NONE:
4682 		passed.mt_count = local.mt_count;
4683 		passed.mt_op = local.mt_op;
4684 		if (ddi_copyout(&passed, (void *)arg, sizeof (passed), flag)) {
4685 			rval = EFAULT;
4686 		}
4687 		break;
4688 	}
4689 #else /* ! _MULTI_DATAMODE */
4690 	if (((uint64_t)local.mt_count) > UINT32_MAX) {
4691 		rval = ERANGE;
4692 	} else {
4693 		passed.mt_op = local.mt_op;
4694 		passed.mt_count = local.mt_count;
4695 		if (ddi_copyout(&passed, (void *)arg, sizeof (passed), flag)) {
4696 			rval = EFAULT;
4697 		}
4698 	}
4699 #endif /* _MULTI_DATAMODE */
4700 
4701 
4702 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4703 	    "st_ioctl: fileno=%x, blkno=%x, eof=%x\n", un->un_pos.fileno,
4704 	    un->un_pos.blkno, un->un_pos.eof);
4705 
4706 	if (un->un_pos.pmode == invalid) {
4707 		un->un_density_known = 0;
4708 	}
4709 
4710 	ASSERT(mutex_owned(ST_MUTEX));
4711 	return (rval);
4712 }
4713 
4714 static int
4715 st_mtiocltop(struct scsi_tape *un, intptr_t arg, int flag)
4716 {
4717 	struct mtlop local;
4718 	int rval;
4719 
4720 	ST_FUNC(ST_DEVINFO, st_mtiocltop);
4721 	if (ddi_copyin((void *)arg, &local, sizeof (local), flag)) {
4722 		return (EFAULT);
4723 	}
4724 
4725 	rval = st_do_mtioctop(un, &local);
4726 
4727 	if (ddi_copyout(&local, (void *)arg, sizeof (local), flag)) {
4728 		rval = EFAULT;
4729 	}
4730 	return (rval);
4731 }
4732 
4733 
4734 static int
4735 st_do_mtioctop(struct scsi_tape *un, struct mtlop *mtop)
4736 {
4737 	dev_t dev = un->un_dev;
4738 	int savefile;
4739 	int rval = 0;
4740 
4741 	ST_FUNC(ST_DEVINFO, st_do_mtioctop);
4742 
4743 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4744 	    "st_do_mtioctop(): mt_op=%x\n", mtop->mt_op);
4745 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4746 	    "fileno=%x, blkno=%x, eof=%x\n",
4747 	    un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
4748 
4749 	un->un_status = 0;
4750 
4751 	/*
4752 	 * if we are going to mess with a tape, we have to make sure we have
4753 	 * one and are not offline (i.e. no tape is initialized).  We let
4754 	 * commands pass here that don't actually touch the tape, except for
4755 	 * loading and initialization (rewinding).
4756 	 */
4757 	if (un->un_state == ST_STATE_OFFLINE) {
4758 		switch (mtop->mt_op) {
4759 		case MTLOAD:
4760 		case MTNOP:
4761 			/*
4762 			 * We don't want strategy calling st_tape_init here,
4763 			 * so, change state
4764 			 */
4765 			un->un_state = ST_STATE_INITIALIZING;
4766 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4767 			    "st_do_mtioctop : OFFLINE state = %d\n",
4768 			    un->un_state);
4769 			break;
4770 		default:
4771 			/*
4772 			 * reinitialize by normal means
4773 			 */
4774 			rval = st_tape_init(dev);
4775 			if (rval) {
4776 				un->un_state = ST_STATE_INITIALIZING;
4777 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4778 				    "st_do_mtioctop : OFFLINE init failure ");
4779 				un->un_state = ST_STATE_OFFLINE;
4780 				un->un_pos.pmode = invalid;
4781 				if (rval != EACCES) {
4782 					rval = EIO;
4783 				}
4784 				return (rval);
4785 			}
4786 			un->un_state = ST_STATE_OPEN_PENDING_IO;
4787 			break;
4788 		}
4789 	}
4790 
4791 	/*
4792 	 * If the file position is invalid, allow only those
4793 	 * commands that properly position the tape and fail
4794 	 * the rest with EIO
4795 	 */
4796 	if (un->un_pos.pmode == invalid) {
4797 		switch (mtop->mt_op) {
4798 		case MTWEOF:
4799 		case MTRETEN:
4800 		case MTERASE:
4801 		case MTEOM:
4802 		case MTFSF:
4803 		case MTFSR:
4804 		case MTBSF:
4805 		case MTNBSF:
4806 		case MTBSR:
4807 		case MTSRSZ:
4808 		case MTGRSZ:
4809 		case MTSEEK:
4810 		case MTBSSF:
4811 		case MTFSSF:
4812 			return (EIO);
4813 			/* NOTREACHED */
4814 		case MTREW:
4815 		case MTLOAD:
4816 		case MTOFFL:
4817 		case MTNOP:
4818 		case MTTELL:
4819 		case MTLOCK:
4820 		case MTUNLOCK:
4821 			break;
4822 
4823 		default:
4824 			return (ENOTTY);
4825 			/* NOTREACHED */
4826 		}
4827 	}
4828 
4829 	switch (mtop->mt_op) {
4830 	case MTERASE:
4831 		/*
4832 		 * MTERASE rewinds the tape, erase it completely, and returns
4833 		 * to the beginning of the tape
4834 		 */
4835 		if (un->un_mspl->wp || un->un_read_only & WORM) {
4836 			un->un_status = KEY_WRITE_PROTECT;
4837 			un->un_err_resid = mtop->mt_count;
4838 			COPY_POS(&un->un_err_pos, &un->un_pos);
4839 			return (EACCES);
4840 		}
4841 		if (un->un_dp->options & ST_REEL) {
4842 			un->un_fmneeded = 2;
4843 		} else {
4844 			un->un_fmneeded = 1;
4845 		}
4846 		if (st_check_density_or_wfm(dev, 1, B_WRITE, NO_STEPBACK) ||
4847 		    st_cmd(dev, SCMD_REWIND, 0, SYNC_CMD) ||
4848 		    st_cmd(dev, SCMD_ERASE, 0, SYNC_CMD)) {
4849 			un->un_pos.pmode = invalid;
4850 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4851 			    "st_do_mtioctop : EIO space or erase or "
4852 			    "check den)\n");
4853 			rval = EIO;
4854 		} else {
4855 			/* QIC and helical scan rewind after erase */
4856 			if (un->un_dp->options & ST_REEL) {
4857 				(void) st_cmd(dev, SCMD_REWIND, 0, ASYNC_CMD);
4858 			}
4859 		}
4860 		break;
4861 
4862 	case MTWEOF:
4863 		/*
4864 		 * write an end-of-file record
4865 		 */
4866 		if (un->un_mspl->wp || un->un_read_only & RDONLY) {
4867 			un->un_status = KEY_WRITE_PROTECT;
4868 			un->un_err_resid = mtop->mt_count;
4869 			COPY_POS(&un->un_err_pos, &un->un_pos);
4870 			return (EACCES);
4871 		}
4872 
4873 		/*
4874 		 * zero count means just flush buffers
4875 		 * negative count is not permitted
4876 		 */
4877 		if (mtop->mt_count < 0) {
4878 			return (EINVAL);
4879 		}
4880 
4881 		/* Not on worm */
4882 		if (un->un_read_only == RDWR) {
4883 			un->un_test_append = 1;
4884 		}
4885 
4886 		if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
4887 			if (st_determine_density(dev, B_WRITE)) {
4888 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4889 				    "st_do_mtioctop : EIO : MTWEOF can't "
4890 				    "determine density");
4891 				return (EIO);
4892 			}
4893 		}
4894 
4895 		rval = st_write_fm(dev, (int)mtop->mt_count);
4896 		if ((rval != 0) && (rval != EACCES)) {
4897 			/*
4898 			 * Failure due to something other than illegal
4899 			 * request results in loss of state (st_intr).
4900 			 */
4901 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4902 			    "st_do_mtioctop : EIO : MTWEOF can't write "
4903 			    "file mark");
4904 			rval = EIO;
4905 		}
4906 		break;
4907 
4908 	case MTRETEN:
4909 		/*
4910 		 * retension the tape
4911 		 */
4912 		if (st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK) ||
4913 		    st_cmd(dev, SCMD_LOAD, LD_LOAD | LD_RETEN, SYNC_CMD)) {
4914 			un->un_pos.pmode = invalid;
4915 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4916 			    "st_do_mtioctop : EIO : MTRETEN ");
4917 			rval = EIO;
4918 		}
4919 		break;
4920 
4921 	case MTREW:
4922 		/*
4923 		 * rewind  the tape
4924 		 */
4925 		if (st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK)) {
4926 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4927 			    "st_do_mtioctop : EIO:MTREW check "
4928 			    "density/wfm failed");
4929 			return (EIO);
4930 		}
4931 		if (st_cmd(dev, SCMD_REWIND, 0, SYNC_CMD)) {
4932 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4933 			    "st_do_mtioctop : EIO : MTREW ");
4934 			rval = EIO;
4935 		}
4936 		break;
4937 
4938 	case MTOFFL:
4939 		/*
4940 		 * rewinds, and, if appropriate, takes the device offline by
4941 		 * unloading the tape
4942 		 */
4943 		if (st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK)) {
4944 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4945 			    "st_do_mtioctop :EIO:MTOFFL check "
4946 			    "density/wfm failed");
4947 			return (EIO);
4948 		}
4949 		(void) st_cmd(dev, SCMD_REWIND, 0, SYNC_CMD);
4950 		if (st_cmd(dev, SCMD_LOAD, LD_UNLOAD, SYNC_CMD)) {
4951 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4952 			    "st_do_mtioctop : EIO : MTOFFL");
4953 			return (EIO);
4954 		}
4955 		un->un_pos.eof = ST_NO_EOF;
4956 		un->un_laststate = un->un_state;
4957 		un->un_state = ST_STATE_OFFLINE;
4958 		un->un_mediastate = MTIO_EJECTED;
4959 		break;
4960 
4961 	case MTLOAD:
4962 		/*
4963 		 * This is to load a tape into the drive
4964 		 * Note that if the tape is not loaded, the device will have
4965 		 * to be opened via O_NDELAY or O_NONBLOCK.
4966 		 */
4967 		/*
4968 		 * Let's try and clean things up, if we are not
4969 		 * initializing, and then send in the load command, no
4970 		 * matter what.
4971 		 *
4972 		 * load after a media change by the user.
4973 		 */
4974 
4975 		if (un->un_state > ST_STATE_INITIALIZING) {
4976 			(void) st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK);
4977 		}
4978 		rval = st_cmd(dev, SCMD_LOAD, LD_LOAD, SYNC_CMD);
4979 		/* Load command to a drive that doesn't support load */
4980 		if ((rval == EIO) &&
4981 		    ((un->un_status == KEY_NOT_READY) &&
4982 			/* Medium not present */
4983 		    (un->un_uscsi_rqs_buf->es_add_code == 0x3a) ||
4984 		    ((un->un_status == KEY_ILLEGAL_REQUEST) &&
4985 		    (un->un_dp->type == MT_ISSTK9840) &&
4986 			/* CSL not present */
4987 		    (un->un_uscsi_rqs_buf->es_add_code == 0x80)))) {
4988 			rval = ENOTTY;
4989 			break;
4990 		} else if (rval != EACCES) {
4991 			rval = EIO;
4992 		}
4993 		if (rval) {
4994 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4995 			    "st_do_mtioctop : %s : MTLOAD\n",
4996 			    rval == EACCES ? "EACCES" : "EIO");
4997 			/*
4998 			 * If load tape fails, who knows what happened...
4999 			 */
5000 			un->un_pos.pmode = invalid;
5001 			break;
5002 		}
5003 
5004 		/*
5005 		 * reset all counters appropriately using rewind, as if LOAD
5006 		 * succeeds, we are at BOT
5007 		 */
5008 		un->un_state = ST_STATE_INITIALIZING;
5009 
5010 		rval = st_tape_init(dev);
5011 		if ((rval == EACCES) && (un->un_read_only & WORM)) {
5012 			rval = 0;
5013 			break;
5014 		}
5015 
5016 		if (rval != 0) {
5017 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5018 			    "st_do_mtioctop : EIO : MTLOAD calls "
5019 			    "st_tape_init\n");
5020 			rval = EIO;
5021 			un->un_state = ST_STATE_OFFLINE;
5022 		}
5023 
5024 		break;
5025 
5026 	case MTNOP:
5027 		un->un_status = 0;		/* Reset status */
5028 		un->un_err_resid = 0;
5029 		mtop->mt_count = MTUNIT(dev);
5030 		break;
5031 
5032 	case MTEOM:
5033 		/*
5034 		 * positions the tape at a location just after the last file
5035 		 * written on the tape. For cartridge and 8 mm, this after
5036 		 * the last file mark; for reel, this is inbetween the two
5037 		 * last 2 file marks
5038 		 */
5039 		if ((un->un_pos.pmode == legacy && un->un_pos.eof >= ST_EOT) ||
5040 		    (un->un_lastop == ST_OP_WRITE) ||
5041 		    (un->un_lastop == ST_OP_WEOF)) {
5042 			/*
5043 			 * If the command wants to move to logical end
5044 			 * of media, and we're already there, we're done.
5045 			 * If we were at logical eot, we reset the state
5046 			 * to be *not* at logical eot.
5047 			 *
5048 			 * If we're at physical or logical eot, we prohibit
5049 			 * forward space operations (unconditionally).
5050 			 *
5051 			 * Also if the last operation was a write of any
5052 			 * kind the tape is at EOD.
5053 			 */
5054 			return (0);
5055 		}
5056 		/*
5057 		 * physical tape position may not be what we've been
5058 		 * telling the user; adjust the request accordingly
5059 		 */
5060 		if (IN_EOF(un->un_pos)) {
5061 			un->un_pos.fileno++;
5062 			un->un_pos.blkno = 0;
5063 		}
5064 
5065 		if (st_check_density_or_wfm(dev, 1, B_READ, NO_STEPBACK)) {
5066 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5067 			    "st_do_mtioctop : EIO:MTEOM check density/wfm "
5068 			    " failed");
5069 			return (EIO);
5070 		}
5071 
5072 		/*
5073 		 * st_find_eod() returns the last fileno we knew about;
5074 		 */
5075 		savefile = st_find_eod(dev);
5076 
5077 		if ((un->un_status != KEY_BLANK_CHECK) &&
5078 		    (un->un_status != SUN_KEY_EOT)) {
5079 			un->un_pos.pmode = invalid;
5080 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5081 			    "st_do_mtioctop : EIO : MTEOM status check failed");
5082 			rval = EIO;
5083 		} else {
5084 			/*
5085 			 * For 1/2" reel tapes assume logical EOT marked
5086 			 * by two file marks or we don't care that we may
5087 			 * be extending the last file on the tape.
5088 			 */
5089 			if (un->un_dp->options & ST_REEL) {
5090 				if (st_cmd(dev, SCMD_SPACE, Fmk((-1)),
5091 				    SYNC_CMD)) {
5092 					un->un_pos.pmode = invalid;
5093 					ST_DEBUG2(ST_DEVINFO, st_label,
5094 					    SCSI_DEBUG,
5095 					    "st_do_mtioctop : EIO : MTEOM space"
5096 					    " cmd failed");
5097 					rval = EIO;
5098 					break;
5099 				}
5100 				/*
5101 				 * Fix up the block number.
5102 				 */
5103 				un->un_pos.blkno = 0;
5104 				un->un_err_pos.blkno = 0;
5105 			}
5106 			un->un_err_resid = 0;
5107 			un->un_pos.fileno = savefile;
5108 			un->un_pos.eof = ST_EOT;
5109 		}
5110 		un->un_status = 0;
5111 		break;
5112 
5113 	case MTFSF:
5114 		rval = st_mtfsf_ioctl(un, mtop->mt_count);
5115 		break;
5116 
5117 	case MTFSR:
5118 		rval = st_mtfsr_ioctl(un, mtop->mt_count);
5119 		break;
5120 
5121 	case MTBSF:
5122 		rval = st_mtbsf_ioctl(un, mtop->mt_count);
5123 		break;
5124 
5125 	case MTNBSF:
5126 		rval = st_mtnbsf_ioctl(un, mtop->mt_count);
5127 		break;
5128 
5129 	case MTBSR:
5130 		rval = st_mtbsr_ioctl(un, mtop->mt_count);
5131 		break;
5132 
5133 	case MTBSSF:
5134 		rval = st_mtbsfm_ioctl(un, mtop->mt_count);
5135 		break;
5136 
5137 	case MTFSSF:
5138 		rval = st_mtfsfm_ioctl(un, mtop->mt_count);
5139 		break;
5140 
5141 	case MTSRSZ:
5142 
5143 		/*
5144 		 * Set record-size to that sent by user
5145 		 * Check to see if there is reason that the requested
5146 		 * block size should not be set.
5147 		 */
5148 
5149 		/* If requesting variable block size is it ok? */
5150 		if ((mtop->mt_count == 0) &&
5151 		    ((un->un_dp->options & ST_VARIABLE) == 0)) {
5152 			return (ENOTTY);
5153 		}
5154 
5155 		/*
5156 		 * If requested block size is not variable "0",
5157 		 * is it less then minimum.
5158 		 */
5159 		if ((mtop->mt_count != 0) &&
5160 		    (mtop->mt_count < un->un_minbsize)) {
5161 			return (EINVAL);
5162 		}
5163 
5164 		/* Is the requested block size more then maximum */
5165 		if ((mtop->mt_count > min(un->un_maxbsize, un->un_maxdma)) &&
5166 		    (un->un_maxbsize != 0)) {
5167 			return (EINVAL);
5168 		}
5169 
5170 		/* Is requested block size a modulus the device likes */
5171 		if ((mtop->mt_count % un->un_data_mod) != 0) {
5172 			return (EINVAL);
5173 		}
5174 
5175 		if (st_change_block_size(dev, (uint32_t)mtop->mt_count) != 0) {
5176 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5177 			    "st_ioctl : MTSRSZ : EIO : cant set block size");
5178 			return (EIO);
5179 		}
5180 
5181 		return (0);
5182 
5183 	case MTGRSZ:
5184 		/*
5185 		 * Get record-size to the user
5186 		 */
5187 		mtop->mt_count = un->un_bsize;
5188 		rval = 0;
5189 		break;
5190 
5191 	case MTTELL:
5192 		rval = st_update_block_pos(un);
5193 		mtop->mt_count = un->un_pos.lgclblkno;
5194 		break;
5195 
5196 	case MTSEEK:
5197 		rval = st_logical_block_locate(un, (uint64_t)mtop->mt_count,
5198 		    un->un_pos.partition);
5199 		/*
5200 		 * This bit of magic make mt print the actual position if
5201 		 * the resulting position was not what was asked for.
5202 		 */
5203 		if (rval == ESPIPE) {
5204 			rval = EIO;
5205 			if ((uint64_t)mtop->mt_count != un->un_pos.lgclblkno) {
5206 				mtop->mt_op = MTTELL;
5207 				mtop->mt_count = un->un_pos.lgclblkno;
5208 			}
5209 		}
5210 		break;
5211 
5212 	case MTLOCK:
5213 		if (st_cmd(dev, SCMD_DOORLOCK, MR_LOCK, SYNC_CMD)) {
5214 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5215 			    "st_do_mtioctop : EIO : MTLOCK");
5216 			rval = EIO;
5217 		}
5218 		break;
5219 
5220 	case MTUNLOCK:
5221 		if (st_cmd(dev, SCMD_DOORLOCK, MR_UNLOCK, SYNC_CMD)) {
5222 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5223 			    "st_do_mtioctop : EIO : MTUNLOCK");
5224 			rval = EIO;
5225 		}
5226 		break;
5227 
5228 	default:
5229 		rval = ENOTTY;
5230 	}
5231 
5232 	return (rval);
5233 }
5234 
5235 
5236 /*
5237  * Run a command for uscsi ioctl.
5238  */
5239 static int
5240 st_ioctl_cmd(dev_t dev, struct uscsi_cmd *ucmd, int flag)
5241 {
5242 	struct uscsi_cmd	*uscmd;
5243 	struct buf	*bp;
5244 	enum uio_seg	uioseg;
5245 	int	offline_state = 0;
5246 	int	err = 0;
5247 
5248 	GET_SOFT_STATE(dev);
5249 
5250 	ST_FUNC(ST_DEVINFO, st_ioctl_cmd);
5251 
5252 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5253 	    "st_ioctl_cmd(dev = 0x%lx)\n", dev);
5254 
5255 	ASSERT(mutex_owned(ST_MUTEX));
5256 
5257 	/*
5258 	 * We really don't know what commands are coming in here and
5259 	 * we don't want to limit the commands coming in.
5260 	 *
5261 	 * If st_tape_init() gets called from st_strategy(), then we
5262 	 * will hang the process waiting for un->un_sbuf_busy to be cleared,
5263 	 * which it never will, as we set it below.  To prevent
5264 	 * st_tape_init() from getting called, we have to set state to other
5265 	 * than ST_STATE_OFFLINE, so we choose ST_STATE_INITIALIZING, which
5266 	 * achieves this purpose already.
5267 	 *
5268 	 * We use offline_state to preserve the OFFLINE state, if it exists,
5269 	 * so other entry points to the driver might have the chance to call
5270 	 * st_tape_init().
5271 	 */
5272 	if (un->un_state == ST_STATE_OFFLINE) {
5273 		un->un_laststate = ST_STATE_OFFLINE;
5274 		un->un_state = ST_STATE_INITIALIZING;
5275 		offline_state = 1;
5276 	}
5277 
5278 	mutex_exit(ST_MUTEX);
5279 	err = scsi_uscsi_alloc_and_copyin((intptr_t)ucmd, flag,
5280 	    ROUTE, &uscmd);
5281 	mutex_enter(ST_MUTEX);
5282 	if (err != 0) {
5283 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5284 		    "st_ioctl_cmd: scsi_uscsi_alloc_and_copyin failed\n");
5285 		goto exit;
5286 	}
5287 
5288 	uioseg = (flag & FKIOCTL) ? UIO_SYSSPACE : UIO_USERSPACE;
5289 
5290 	/* check to see if this command requires the drive to be reserved */
5291 	if (uscmd->uscsi_cdb != NULL) {
5292 		err = st_check_cdb_for_need_to_reserve(un,
5293 		    &((char *)uscmd->uscsi_cdb)[0]);
5294 		if (err) {
5295 			goto exit_free;
5296 		}
5297 	}
5298 
5299 	/*
5300 	 * Get buffer resources...
5301 	 */
5302 	while (un->un_sbuf_busy)
5303 		cv_wait(&un->un_sbuf_cv, ST_MUTEX);
5304 	un->un_sbuf_busy = 1;
5305 
5306 #ifdef STDEBUG
5307 	if ((uscmd->uscsi_cdb != NULL) && (st_debug & 0xf) > 6) {
5308 		int rw = (uscmd->uscsi_flags & USCSI_READ) ? B_READ : B_WRITE;
5309 		st_print_cdb(ST_DEVINFO, st_label, SCSI_DEBUG,
5310 		    "uscsi cdb", uscmd->uscsi_cdb);
5311 		if (uscmd->uscsi_buflen) {
5312 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
5313 			    "uscsi %s of %ld bytes %s %s space\n",
5314 			    (rw == B_READ) ? rd_str : wr_str,
5315 			    uscmd->uscsi_buflen,
5316 			    (rw == B_READ) ? "to" : "from",
5317 			    (uioseg == UIO_SYSSPACE) ? "system" : "user");
5318 		}
5319 	}
5320 #endif /* ST_DEBUG */
5321 
5322 	/*
5323 	 * Although st_ioctl_cmd() never makes use of these
5324 	 * now, we are just being safe and consistent.
5325 	 */
5326 	uscmd->uscsi_flags &= ~(USCSI_NOINTR | USCSI_NOPARITY |
5327 	    USCSI_OTAG | USCSI_HTAG | USCSI_HEAD);
5328 
5329 	un->un_srqbufp = uscmd->uscsi_rqbuf;
5330 	bp = un->un_sbufp;
5331 	bzero(bp, sizeof (buf_t));
5332 	if (uscmd->uscsi_cdb != NULL) {
5333 		bp->b_forw =
5334 		    (struct buf *)(uintptr_t)((char *)uscmd->uscsi_cdb)[0];
5335 		bp->b_back = (struct buf *)uscmd;
5336 	}
5337 
5338 	mutex_exit(ST_MUTEX);
5339 	err = scsi_uscsi_handle_cmd(dev, uioseg, uscmd,
5340 	    st_strategy, bp, NULL);
5341 	mutex_enter(ST_MUTEX);
5342 
5343 	/*
5344 	 * If scsi reset successful, don't write any filemarks.
5345 	 */
5346 	if ((err == 0) && (uscmd->uscsi_flags &
5347 	    (USCSI_RESET_LUN | USCSI_RESET_TARGET | USCSI_RESET_ALL))) {
5348 		un->un_fmneeded = 0;
5349 	}
5350 
5351 exit_free:
5352 	/*
5353 	 * Free resources
5354 	 */
5355 	un->un_sbuf_busy = 0;
5356 	un->un_srqbufp = NULL;
5357 
5358 	/*
5359 	 * If was a space command need to update logical block position.
5360 	 * If the command failed such that positioning is invalid, Don't
5361 	 * update the position as the user must do this to validate the
5362 	 * position for data protection.
5363 	 */
5364 	if ((uscmd->uscsi_cdb[0] == SCMD_SPACE) &&
5365 	    (un->un_pos.pmode != invalid)) {
5366 		uchar_t status = un->un_status;
5367 		(void) st_update_block_pos(un);
5368 		un->un_status = status;
5369 	}
5370 	cv_signal(&un->un_sbuf_cv);
5371 	mutex_exit(ST_MUTEX);
5372 	(void) scsi_uscsi_copyout_and_free((intptr_t)ucmd, uscmd);
5373 	mutex_enter(ST_MUTEX);
5374 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
5375 	    "st_ioctl_cmd returns 0x%x\n", err);
5376 
5377 exit:
5378 	/* don't lose offline state */
5379 	if (offline_state) {
5380 		un->un_state = ST_STATE_OFFLINE;
5381 	}
5382 
5383 	ASSERT(mutex_owned(ST_MUTEX));
5384 	return (err);
5385 }
5386 
5387 static int
5388 st_write_fm(dev_t dev, int wfm)
5389 {
5390 	int i;
5391 	int rval;
5392 
5393 	GET_SOFT_STATE(dev);
5394 
5395 	ST_FUNC(ST_DEVINFO, st_write_fm);
5396 
5397 	ASSERT(mutex_owned(ST_MUTEX));
5398 
5399 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5400 	    "st_write_fm(dev = 0x%lx, wfm = %d)\n", dev, wfm);
5401 
5402 	/*
5403 	 * write one filemark at the time after EOT
5404 	 */
5405 	if (un->un_pos.eof >= ST_EOT) {
5406 		for (i = 0; i < wfm; i++) {
5407 			rval = st_cmd(dev, SCMD_WRITE_FILE_MARK, 1, SYNC_CMD);
5408 			if (rval == EACCES) {
5409 				return (rval);
5410 			}
5411 			if (rval != 0) {
5412 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5413 				    "st_write_fm : EIO : write EOT file mark");
5414 				return (EIO);
5415 			}
5416 		}
5417 	} else {
5418 		rval = st_cmd(dev, SCMD_WRITE_FILE_MARK, wfm, SYNC_CMD);
5419 		if (rval == EACCES) {
5420 			return (rval);
5421 		}
5422 		if (rval) {
5423 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5424 			    "st_write_fm : EIO : write file mark");
5425 			return (EIO);
5426 		}
5427 	}
5428 
5429 	ASSERT(mutex_owned(ST_MUTEX));
5430 	return (0);
5431 }
5432 
5433 #ifdef STDEBUG
5434 static void
5435 start_dump(struct scsi_tape *un, struct buf *bp)
5436 {
5437 	struct scsi_pkt *pkt = BP_PKT(bp);
5438 	uchar_t *cdbp = (uchar_t *)pkt->pkt_cdbp;
5439 
5440 	ST_FUNC(ST_DEVINFO, start_dump);
5441 
5442 	if ((st_debug & 0xf) < 6)
5443 		return;
5444 	scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
5445 	    "st_start: cmd=0x%p count=%ld resid=%ld flags=0x%x pkt=0x%p\n",
5446 	    (void *)bp->b_forw, bp->b_bcount,
5447 	    bp->b_resid, bp->b_flags, (void *)BP_PKT(bp));
5448 
5449 	st_print_cdb(ST_DEVINFO, st_label, SCSI_DEBUG,
5450 	    "st_start: cdb",  (caddr_t)cdbp);
5451 	scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
5452 	    "st_start: fileno=%d, blk=%d\n",
5453 	    un->un_pos.fileno, un->un_pos.blkno);
5454 }
5455 #endif
5456 
5457 
5458 /*
5459  * Command start && done functions
5460  */
5461 
5462 /*
5463  * st_start()
5464  *
5465  * Called from:
5466  *  st_strategy() to start a command.
5467  *  st_runout() to retry when scsi_pkt allocation fails on previous attempt(s).
5468  *  st_attach() when resuming from power down state.
5469  *  st_start_restart() to retry transport when device was previously busy.
5470  *  st_done_and_mutex_exit() to start the next command when previous is done.
5471  *
5472  * On entry:
5473  *  scsi_pkt may or may not be allocated.
5474  *
5475  */
5476 static void
5477 st_start(struct scsi_tape *un)
5478 {
5479 	struct buf *bp;
5480 	int status;
5481 
5482 	ST_FUNC(ST_DEVINFO, st_start);
5483 	ASSERT(mutex_owned(ST_MUTEX));
5484 
5485 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5486 	    "st_start(): dev = 0x%lx\n", un->un_dev);
5487 
5488 	if ((bp = un->un_quef) == NULL) {
5489 		return;
5490 	}
5491 
5492 	ASSERT((bp->b_flags & B_DONE) == 0);
5493 
5494 	/*
5495 	 * Don't send more than un_throttle commands to the HBA
5496 	 */
5497 	if ((un->un_throttle <= 0) || (un->un_ncmds >= un->un_throttle)) {
5498 		return;
5499 	}
5500 
5501 	/*
5502 	 * If the buf has no scsi_pkt call st_make_cmd() to get one and
5503 	 * build the command.
5504 	 */
5505 	if (BP_PKT(bp) == NULL) {
5506 		ASSERT((bp->b_flags & B_DONE) == 0);
5507 		st_make_cmd(un, bp, st_runout);
5508 		ASSERT((bp->b_flags & B_DONE) == 0);
5509 		status = geterror(bp);
5510 
5511 		/*
5512 		 * Some HBA's don't call bioerror() to set an error.
5513 		 * And geterror() returns zero if B_ERROR is not set.
5514 		 * So if we get zero we must check b_error.
5515 		 */
5516 		if (status == 0 && bp->b_error != 0) {
5517 			status = bp->b_error;
5518 			bioerror(bp, status);
5519 		}
5520 
5521 		/*
5522 		 * Some HBA's convert DDI_DMA_NORESOURCES into ENOMEM.
5523 		 * In tape ENOMEM has special meaning so we'll change it.
5524 		 */
5525 		if (status == ENOMEM) {
5526 			status = 0;
5527 			bioerror(bp, status);
5528 		}
5529 
5530 		/*
5531 		 * Did it fail and is it retryable?
5532 		 * If so return and wait for the callback through st_runout.
5533 		 * Also looks like scsi_init_pkt() will setup a callback even
5534 		 * if it isn't retryable.
5535 		 */
5536 		if (BP_PKT(bp) == NULL) {
5537 			if (status == 0) {
5538 				/*
5539 				 * If first attempt save state.
5540 				 */
5541 				if (un->un_state != ST_STATE_RESOURCE_WAIT) {
5542 					un->un_laststate = un->un_state;
5543 					un->un_state = ST_STATE_RESOURCE_WAIT;
5544 				}
5545 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5546 				    "temp no resources for pkt\n");
5547 			} else {
5548 				/*
5549 				 * Unlikely that it would be retryable then not.
5550 				 */
5551 				if (un->un_state == ST_STATE_RESOURCE_WAIT) {
5552 					un->un_state = un->un_laststate;
5553 				}
5554 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
5555 				    "perm no resources for pkt errno = 0x%x\n",
5556 				    status);
5557 			}
5558 			return;
5559 		}
5560 		/*
5561 		 * Worked this time set the state back.
5562 		 */
5563 		if (un->un_state == ST_STATE_RESOURCE_WAIT) {
5564 			un->un_state = un->un_laststate;
5565 		}
5566 	}
5567 
5568 	/*
5569 	 * move from waitq to runq
5570 	 */
5571 	un->un_quef = bp->b_actf;
5572 	if (un->un_quel == bp) {
5573 		/*
5574 		 *  For the case of queue having one
5575 		 *  element, set the tail pointer to
5576 		 *  point to the element.
5577 		 */
5578 		un->un_quel = bp->b_actf;
5579 	}
5580 
5581 	bp->b_actf = NULL;
5582 
5583 	if (un->un_runqf) {
5584 		un->un_runql->b_actf = bp;
5585 	} else {
5586 		un->un_runqf = bp;
5587 	}
5588 	un->un_runql = bp;
5589 
5590 
5591 	ST_CDB(ST_DEVINFO, "Start CDB", (char *)BP_PKT(bp)->pkt_cdbp);
5592 
5593 #ifdef STDEBUG
5594 	start_dump(un, bp);
5595 #endif
5596 
5597 	/* could not get here if throttle was zero */
5598 	un->un_last_throttle = un->un_throttle;
5599 	un->un_throttle = 0;	/* so nothing else will come in here */
5600 	un->un_ncmds++;
5601 
5602 	ST_DO_KSTATS(bp, kstat_waitq_to_runq);
5603 
5604 	mutex_exit(ST_MUTEX);
5605 
5606 	status = scsi_transport(BP_PKT(bp));
5607 
5608 	mutex_enter(ST_MUTEX);
5609 
5610 	if (un->un_last_throttle) {
5611 		un->un_throttle = un->un_last_throttle;
5612 	}
5613 
5614 	if (status != TRAN_ACCEPT) {
5615 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
5616 		mutex_exit(ST_MUTEX);
5617 
5618 		if (status == TRAN_BUSY) {
5619 			/* if too many retries, fail the transport */
5620 			if (st_handle_start_busy(un, bp,
5621 			    ST_TRAN_BUSY_TIMEOUT) == 0)
5622 				goto done;
5623 		}
5624 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
5625 		    "transport rejected\n");
5626 		bp->b_resid = bp->b_bcount;
5627 
5628 
5629 #ifndef __lock_lint
5630 		/*
5631 		 * warlock doesn't understand this potential
5632 		 * recursion?
5633 		 */
5634 		mutex_enter(ST_MUTEX);
5635 		ST_DO_KSTATS(bp, kstat_waitq_exit);
5636 		ST_DO_ERRSTATS(un, st_transerrs);
5637 		st_bioerror(bp, EIO);
5638 		SET_PE_FLAG(un);
5639 		st_done_and_mutex_exit(un, bp);
5640 #endif
5641 	} else {
5642 		un->un_tran_retry_ct = 0;
5643 		mutex_exit(ST_MUTEX);
5644 	}
5645 
5646 done:
5647 
5648 	mutex_enter(ST_MUTEX);
5649 }
5650 
5651 /*
5652  * if the transport is busy, then put this bp back on the waitq
5653  */
5654 static int
5655 st_handle_start_busy(struct scsi_tape *un, struct buf *bp,
5656     clock_t timeout_interval)
5657 {
5658 	struct buf *last_quef, *runq_bp;
5659 	int rval = 0;
5660 
5661 	ST_FUNC(ST_DEVINFO, st_handle_start_busy);
5662 
5663 	mutex_enter(ST_MUTEX);
5664 
5665 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5666 	    "st_handle_start_busy()\n");
5667 
5668 	/*
5669 	 * Check to see if we hit the retry timeout and one last check for
5670 	 * making sure this is the last on the runq, if it is not, we have
5671 	 * to fail
5672 	 */
5673 	if (((int)un->un_tran_retry_ct++ > st_retry_count) ||
5674 	    (un->un_runql != bp)) {
5675 		rval = -1;
5676 		goto exit;
5677 	}
5678 
5679 	/* put the bp back on the waitq */
5680 	if (un->un_quef) {
5681 		last_quef = un->un_quef;
5682 		un->un_quef = bp;
5683 		bp->b_actf = last_quef;
5684 	} else  {
5685 		bp->b_actf = NULL;
5686 		un->un_quef = bp;
5687 		un->un_quel = bp;
5688 	}
5689 
5690 	/*
5691 	 * Decrement un_ncmds so that this
5692 	 * gets thru' st_start() again.
5693 	 */
5694 	un->un_ncmds--;
5695 
5696 	/*
5697 	 * since this is an error case, we won't have to do
5698 	 * this list walking much.  We've already made sure this bp was the
5699 	 * last on the runq
5700 	 */
5701 	runq_bp = un->un_runqf;
5702 
5703 	if (un->un_runqf == bp) {
5704 		un->un_runqf = NULL;
5705 		un->un_runql = NULL;
5706 	} else {
5707 		while (runq_bp) {
5708 			if (runq_bp->b_actf == bp) {
5709 				runq_bp->b_actf = NULL;
5710 				un->un_runql = runq_bp;
5711 				break;
5712 			}
5713 			runq_bp = runq_bp->b_actf;
5714 		}
5715 	}
5716 
5717 
5718 	/*
5719 	 * send a marker pkt, if appropriate
5720 	 */
5721 	st_hba_unflush(un);
5722 
5723 	/*
5724 	 * all queues are aligned, we are just waiting to
5725 	 * transport, don't alloc any more buf p's, when
5726 	 * st_start is reentered.
5727 	 */
5728 	(void) timeout(st_start_restart, un, timeout_interval);
5729 
5730 exit:
5731 	mutex_exit(ST_MUTEX);
5732 	return (rval);
5733 }
5734 
5735 
5736 /*
5737  * st_runout a callback that is called what a resource allocatation failed
5738  */
5739 static int
5740 st_runout(caddr_t arg)
5741 {
5742 	struct scsi_tape *un = (struct scsi_tape *)arg;
5743 	struct buf *bp;
5744 	ASSERT(un != NULL);
5745 
5746 	ST_FUNC(ST_DEVINFO, st_runout);
5747 
5748 	mutex_enter(ST_MUTEX);
5749 
5750 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_runout()\n");
5751 
5752 	bp = un->un_quef;
5753 
5754 	/*
5755 	 * failed scsi_init_pkt(). If errno is zero its retryable.
5756 	 */
5757 	if ((bp != NULL) && (geterror(bp) != 0)) {
5758 
5759 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
5760 		    "errors after pkt alloc (b_flags=0x%x, b_error=0x%x)\n",
5761 		    bp->b_flags, geterror(bp));
5762 		ASSERT((bp->b_flags & B_DONE) == 0);
5763 
5764 		un->un_quef = bp->b_actf;
5765 		if (un->un_quel == bp) {
5766 			/*
5767 			 *  For the case of queue having one
5768 			 *  element, set the tail pointer to
5769 			 *  point to the element.
5770 			 */
5771 			un->un_quel = bp->b_actf;
5772 		}
5773 		mutex_exit(ST_MUTEX);
5774 		bp->b_actf = NULL;
5775 
5776 		ASSERT((bp->b_flags & B_DONE) == 0);
5777 
5778 		/*
5779 		 * Set resid, Error already set, then unblock calling thread.
5780 		 */
5781 		bp->b_resid = bp->b_bcount;
5782 		biodone(bp);
5783 	} else {
5784 		/*
5785 		 * Try Again
5786 		 */
5787 		st_start(un);
5788 		mutex_exit(ST_MUTEX);
5789 	}
5790 
5791 	/*
5792 	 * Comments courtesy of sd.c
5793 	 * The scsi_init_pkt routine allows for the callback function to
5794 	 * return a 0 indicating the callback should be rescheduled or a 1
5795 	 * indicating not to reschedule. This routine always returns 1
5796 	 * because the driver always provides a callback function to
5797 	 * scsi_init_pkt. This results in a callback always being scheduled
5798 	 * (via the scsi_init_pkt callback implementation) if a resource
5799 	 * failure occurs.
5800 	 */
5801 
5802 	return (1);
5803 }
5804 
5805 /*
5806  * st_done_and_mutex_exit()
5807  *	- remove bp from runq
5808  *	- start up the next request
5809  *	- if this was an asynch bp, clean up
5810  *	- exit with released mutex
5811  */
5812 static void
5813 st_done_and_mutex_exit(struct scsi_tape *un, struct buf *bp)
5814 {
5815 	struct buf *runqbp, *prevbp;
5816 	int	pe_flagged = 0;
5817 
5818 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
5819 #if !defined(lint)
5820 	_NOTE(LOCK_RELEASED_AS_SIDE_EFFECT(&un->un_sd->sd_mutex))
5821 #endif
5822 
5823 	ST_FUNC(ST_DEVINFO, st_done_and_mutex_exit);
5824 
5825 	ASSERT(mutex_owned(ST_MUTEX));
5826 
5827 	/*
5828 	 * if bp is still on the runq (anywhere), then remove it
5829 	 */
5830 	prevbp = NULL;
5831 	for (runqbp = un->un_runqf; runqbp != 0; runqbp = runqbp->b_actf) {
5832 		if (runqbp == bp) {
5833 			if (runqbp == un->un_runqf) {
5834 				un->un_runqf = bp->b_actf;
5835 			} else {
5836 				prevbp->b_actf = bp->b_actf;
5837 			}
5838 			if (un->un_runql == bp) {
5839 				un->un_runql = prevbp;
5840 			}
5841 			break;
5842 		}
5843 		prevbp = runqbp;
5844 	}
5845 	bp->b_actf = NULL;
5846 
5847 	un->un_ncmds--;
5848 	cv_signal(&un->un_queue_cv);
5849 
5850 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5851 	    "st_done_and_mutex_exit(): cmd=0x%x count=%ld resid=%ld  flags="
5852 	    "0x%x\n", (uchar_t)*((caddr_t)(BP_PKT(bp))->pkt_cdbp), bp->b_bcount,
5853 	    bp->b_resid, bp->b_flags);
5854 
5855 
5856 	/*
5857 	 * update kstats with transfer count info
5858 	 */
5859 	if (un->un_stats && (bp != un->un_sbufp) && IS_RW(bp)) {
5860 		uint32_t n_done =  bp->b_bcount - bp->b_resid;
5861 		if (bp->b_flags & B_READ) {
5862 			IOSP->reads++;
5863 			IOSP->nread += n_done;
5864 		} else {
5865 			IOSP->writes++;
5866 			IOSP->nwritten += n_done;
5867 		}
5868 	}
5869 
5870 	/*
5871 	 * Start the next one before releasing resources on this one, if
5872 	 * there is something on the queue and persistent errors has not been
5873 	 * flagged
5874 	 */
5875 
5876 	if ((pe_flagged = IS_PE_FLAG_SET(un)) != 0) {
5877 		un->un_last_resid = bp->b_resid;
5878 		un->un_last_count = bp->b_bcount;
5879 	}
5880 
5881 	if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
5882 		cv_broadcast(&un->un_tape_busy_cv);
5883 	} else if (un->un_quef && un->un_throttle && !pe_flagged) {
5884 		st_start(un);
5885 	}
5886 
5887 	if (bp == un->un_sbufp && (bp->b_flags & B_ASYNC)) {
5888 		/*
5889 		 * Since we marked this ourselves as ASYNC,
5890 		 * there isn't anybody around waiting for
5891 		 * completion any more.
5892 		 */
5893 		uchar_t com = (uchar_t)(uintptr_t)bp->b_forw;
5894 		if (com == SCMD_READ || com == SCMD_WRITE) {
5895 			bp->b_un.b_addr = (caddr_t)0;
5896 		}
5897 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
5898 		    "st_done_and_mutex_exit(async): freeing pkt\n");
5899 		scsi_destroy_pkt(BP_PKT(bp));
5900 		un->un_sbuf_busy = 0;
5901 		cv_signal(&un->un_sbuf_cv);
5902 		mutex_exit(ST_MUTEX);
5903 		return;
5904 	}
5905 
5906 	if (bp == un->un_sbufp && BP_UCMD(bp)) {
5907 		/*
5908 		 * Copy status from scsi_pkt to uscsi_cmd
5909 		 * since st_ioctl_cmd needs it
5910 		 */
5911 		BP_UCMD(bp)->uscsi_status = SCBP_C(BP_PKT(bp));
5912 	}
5913 
5914 
5915 #ifdef STDEBUG
5916 	if (((st_debug & 0xf) >= 4) &&
5917 	    (((un->un_pos.blkno % 100) == 0) || IS_PE_FLAG_SET(un))) {
5918 
5919 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
5920 		    "st_d_a_m_exit(): ncmds = %d, thr = %d, "
5921 		    "un_errno = %d, un_pe = %d\n",
5922 		    un->un_ncmds, un->un_throttle, un->un_errno,
5923 		    un->un_persist_errors);
5924 	}
5925 
5926 #endif
5927 
5928 	mutex_exit(ST_MUTEX);
5929 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
5930 	    "st_done_and_mutex_exit: freeing pkt\n");
5931 
5932 	scsi_destroy_pkt(BP_PKT(bp));
5933 
5934 	biodone(bp);
5935 
5936 	/*
5937 	 * now that we biodoned that command, if persistent errors have been
5938 	 * flagged, flush the waitq
5939 	 */
5940 	if (pe_flagged)
5941 		st_flush(un);
5942 }
5943 
5944 
5945 /*
5946  * Tape error, flush tape driver queue.
5947  */
5948 static void
5949 st_flush(struct scsi_tape *un)
5950 {
5951 	struct buf *bp;
5952 
5953 	ST_FUNC(ST_DEVINFO, st_flush);
5954 
5955 	mutex_enter(ST_MUTEX);
5956 
5957 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
5958 	    "st_flush(), ncmds = %d, quef = 0x%p\n",
5959 	    un->un_ncmds, (void *)un->un_quef);
5960 
5961 	/*
5962 	 * if we still have commands outstanding, wait for them to come in
5963 	 * before flushing the queue, and make sure there is a queue
5964 	 */
5965 	if (un->un_ncmds || !un->un_quef)
5966 		goto exit;
5967 
5968 	/*
5969 	 * we have no more commands outstanding, so let's deal with special
5970 	 * cases in the queue for EOM and FM. If we are here, and un_errno
5971 	 * is 0, then we know there was no error and we return a 0 read or
5972 	 * write before showing errors
5973 	 */
5974 
5975 	/* Flush the wait queue. */
5976 	while ((bp = un->un_quef) != NULL) {
5977 		un->un_quef = bp->b_actf;
5978 
5979 		bp->b_resid = bp->b_bcount;
5980 
5981 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
5982 		    "st_flush() : blkno=%d, err=%d, b_bcount=%ld\n",
5983 		    un->un_pos.blkno, un->un_errno, bp->b_bcount);
5984 
5985 		st_set_pe_errno(un);
5986 
5987 		bioerror(bp, un->un_errno);
5988 
5989 		mutex_exit(ST_MUTEX);
5990 		/* it should have one, but check anyway */
5991 		if (BP_PKT(bp)) {
5992 			scsi_destroy_pkt(BP_PKT(bp));
5993 		}
5994 		biodone(bp);
5995 		mutex_enter(ST_MUTEX);
5996 	}
5997 
5998 	/*
5999 	 * It's not a bad practice to reset the
6000 	 * waitq tail pointer to NULL.
6001 	 */
6002 	un->un_quel = NULL;
6003 
6004 exit:
6005 	/* we mucked with the queue, so let others know about it */
6006 	cv_signal(&un->un_queue_cv);
6007 	mutex_exit(ST_MUTEX);
6008 }
6009 
6010 
6011 /*
6012  * Utility functions
6013  */
6014 static int
6015 st_determine_generic(dev_t dev)
6016 {
6017 	int bsize;
6018 	static char *cart = "0.25 inch cartridge";
6019 	char *sizestr;
6020 
6021 	GET_SOFT_STATE(dev);
6022 
6023 	ST_FUNC(ST_DEVINFO, st_determine_generic);
6024 
6025 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6026 	    "st_determine_generic(dev = 0x%lx)\n", dev);
6027 
6028 	ASSERT(mutex_owned(ST_MUTEX));
6029 
6030 	if (st_modesense(un)) {
6031 		return (-1);
6032 	}
6033 
6034 	bsize = (un->un_mspl->high_bl << 16)	|
6035 	    (un->un_mspl->mid_bl << 8)	|
6036 	    (un->un_mspl->low_bl);
6037 
6038 	if (bsize == 0) {
6039 		un->un_dp->options |= ST_VARIABLE;
6040 		un->un_dp->bsize = 0;
6041 		un->un_bsize = 0;
6042 	} else if (bsize > ST_MAXRECSIZE_FIXED) {
6043 		/*
6044 		 * record size of this device too big.
6045 		 * try and convert it to variable record length.
6046 		 *
6047 		 */
6048 		un->un_dp->options |= ST_VARIABLE;
6049 		if (st_change_block_size(dev, 0) != 0) {
6050 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
6051 			    "Fixed Record Size %d is too large\n", bsize);
6052 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
6053 			    "Cannot switch to variable record size\n");
6054 			un->un_dp->options &= ~ST_VARIABLE;
6055 			return (-1);
6056 		}
6057 	} else if (st_change_block_size(dev, 0) == 0) {
6058 		/*
6059 		 * If the drive was set to a non zero block size,
6060 		 * See if it can be set to a zero block size.
6061 		 * If it works, ST_VARIABLE so user can set it as they want.
6062 		 */
6063 		un->un_dp->options |= ST_VARIABLE;
6064 		un->un_dp->bsize = 0;
6065 		un->un_bsize = 0;
6066 	} else {
6067 		un->un_dp->bsize = bsize;
6068 		un->un_bsize = bsize;
6069 	}
6070 
6071 
6072 	switch (un->un_mspl->density) {
6073 	default:
6074 	case 0x0:
6075 		/*
6076 		 * default density, cannot determine any other
6077 		 * information.
6078 		 */
6079 		sizestr = "Unknown type- assuming 0.25 inch cartridge";
6080 		un->un_dp->type = ST_TYPE_DEFAULT;
6081 		un->un_dp->options |= (ST_AUTODEN_OVERRIDE|ST_QIC);
6082 		break;
6083 	case 0x1:
6084 	case 0x2:
6085 	case 0x3:
6086 	case 0x6:
6087 		/*
6088 		 * 1/2" reel
6089 		 */
6090 		sizestr = "0.50 inch reel";
6091 		un->un_dp->type = ST_TYPE_REEL;
6092 		un->un_dp->options |= ST_REEL;
6093 		un->un_dp->densities[0] = 0x1;
6094 		un->un_dp->densities[1] = 0x2;
6095 		un->un_dp->densities[2] = 0x6;
6096 		un->un_dp->densities[3] = 0x3;
6097 		break;
6098 	case 0x4:
6099 	case 0x5:
6100 	case 0x7:
6101 	case 0x0b:
6102 
6103 		/*
6104 		 * Quarter inch.
6105 		 */
6106 		sizestr = cart;
6107 		un->un_dp->type = ST_TYPE_DEFAULT;
6108 		un->un_dp->options |= ST_QIC;
6109 
6110 		un->un_dp->densities[1] = 0x4;
6111 		un->un_dp->densities[2] = 0x5;
6112 		un->un_dp->densities[3] = 0x7;
6113 		un->un_dp->densities[0] = 0x0b;
6114 		break;
6115 
6116 	case 0x0f:
6117 	case 0x10:
6118 	case 0x11:
6119 	case 0x12:
6120 		/*
6121 		 * QIC-120, QIC-150, QIC-320, QIC-600
6122 		 */
6123 		sizestr = cart;
6124 		un->un_dp->type = ST_TYPE_DEFAULT;
6125 		un->un_dp->options |= ST_QIC;
6126 		un->un_dp->densities[0] = 0x0f;
6127 		un->un_dp->densities[1] = 0x10;
6128 		un->un_dp->densities[2] = 0x11;
6129 		un->un_dp->densities[3] = 0x12;
6130 		break;
6131 
6132 	case 0x09:
6133 	case 0x0a:
6134 	case 0x0c:
6135 	case 0x0d:
6136 		/*
6137 		 * 1/2" cartridge tapes. Include HI-TC.
6138 		 */
6139 		sizestr = cart;
6140 		sizestr[2] = '5';
6141 		sizestr[3] = '0';
6142 		un->un_dp->type = ST_TYPE_HIC;
6143 		un->un_dp->densities[0] = 0x09;
6144 		un->un_dp->densities[1] = 0x0a;
6145 		un->un_dp->densities[2] = 0x0c;
6146 		un->un_dp->densities[3] = 0x0d;
6147 		break;
6148 
6149 	case 0x13:
6150 			/* DDS-2/DDS-3 scsi spec densities */
6151 	case 0x24:
6152 	case 0x25:
6153 	case 0x26:
6154 		sizestr = "DAT Data Storage (DDS)";
6155 		un->un_dp->type = ST_TYPE_DAT;
6156 		un->un_dp->options |= ST_AUTODEN_OVERRIDE;
6157 		break;
6158 
6159 	case 0x14:
6160 		/*
6161 		 * Helical Scan (Exabyte) devices
6162 		 */
6163 		sizestr = "8mm helical scan cartridge";
6164 		un->un_dp->type = ST_TYPE_EXABYTE;
6165 		un->un_dp->options |= ST_AUTODEN_OVERRIDE;
6166 		break;
6167 	}
6168 
6169 	/*
6170 	 * Assume LONG ERASE, BSF and BSR
6171 	 */
6172 
6173 	un->un_dp->options |=
6174 	    (ST_LONG_ERASE | ST_UNLOADABLE | ST_BSF | ST_BSR | ST_KNOWS_EOD);
6175 
6176 	/*
6177 	 * Only if mode sense data says no buffered write, set NOBUF
6178 	 */
6179 	if (un->un_mspl->bufm == 0)
6180 		un->un_dp->options |= ST_NOBUF;
6181 
6182 	/*
6183 	 * set up large read and write retry counts
6184 	 */
6185 
6186 	un->un_dp->max_rretries = un->un_dp->max_wretries = 1000;
6187 
6188 	/*
6189 	 * If this is a 0.50 inch reel tape, and
6190 	 * it is *not* variable mode, try and
6191 	 * set it to variable record length
6192 	 * mode.
6193 	 */
6194 	if ((un->un_dp->options & ST_REEL) && un->un_bsize != 0 &&
6195 	    (un->un_dp->options & ST_VARIABLE)) {
6196 		if (st_change_block_size(dev, 0) == 0) {
6197 			un->un_dp->bsize = 0;
6198 			un->un_mspl->high_bl = un->un_mspl->mid_bl =
6199 			    un->un_mspl->low_bl = 0;
6200 		}
6201 	}
6202 
6203 	/*
6204 	 * Write to console about type of device found
6205 	 */
6206 	ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
6207 	    "Generic Drive, Vendor=%s\n\t%s", un->un_dp->name,
6208 	    sizestr);
6209 	if (un->un_dp->options & ST_VARIABLE) {
6210 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
6211 		    "!Variable record length I/O\n");
6212 	} else {
6213 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
6214 		    "!Fixed record length (%d byte blocks) I/O\n",
6215 		    un->un_dp->bsize);
6216 	}
6217 	ASSERT(mutex_owned(ST_MUTEX));
6218 	return (0);
6219 }
6220 
6221 static int
6222 st_determine_density(dev_t dev, int rw)
6223 {
6224 	int rval = 0;
6225 
6226 	GET_SOFT_STATE(dev);
6227 
6228 	ST_FUNC(ST_DEVINFO, st_determine_density);
6229 
6230 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6231 	    "st_determine_density(dev = 0x%lx, rw = %s)\n",
6232 	    dev, (rw == B_WRITE ? wr_str: rd_str));
6233 
6234 	ASSERT(mutex_owned(ST_MUTEX));
6235 
6236 	/*
6237 	 * If we're past BOT, density is determined already.
6238 	 */
6239 	if (un->un_pos.pmode == logical) {
6240 		if (un->un_pos.lgclblkno != 0) {
6241 			goto exit;
6242 		}
6243 	} else if (un->un_pos.pmode == legacy) {
6244 		if ((un->un_pos.fileno != 0) || (un->un_pos.blkno != 0)) {
6245 			/*
6246 			 * XXX: put in a bitch message about attempting to
6247 			 * XXX: change density past BOT.
6248 			 */
6249 			goto exit;
6250 		}
6251 	} else {
6252 		goto exit;
6253 	}
6254 
6255 
6256 	/*
6257 	 * If we're going to be writing, we set the density
6258 	 */
6259 	if (rw == 0 || rw == B_WRITE) {
6260 		/* un_curdens is used as an index into densities table */
6261 		un->un_curdens = MT_DENSITY(un->un_dev);
6262 		if (st_set_density(dev)) {
6263 			rval = -1;
6264 		}
6265 		goto exit;
6266 	}
6267 
6268 	/*
6269 	 * If density is known already,
6270 	 * we don't have to get it again.(?)
6271 	 */
6272 	if (!un->un_density_known) {
6273 		if (st_get_density(dev)) {
6274 			rval = -1;
6275 		}
6276 	}
6277 
6278 exit:
6279 	ASSERT(mutex_owned(ST_MUTEX));
6280 	return (rval);
6281 }
6282 
6283 
6284 /*
6285  * Try to determine density. We do this by attempting to read the
6286  * first record off the tape, cycling through the available density
6287  * codes as we go.
6288  */
6289 
6290 static int
6291 st_get_density(dev_t dev)
6292 {
6293 	int succes = 0, rval = -1, i;
6294 	uint_t size;
6295 	uchar_t dens, olddens;
6296 
6297 	GET_SOFT_STATE(dev);
6298 
6299 	ST_FUNC(ST_DEVINFO, st_get_density);
6300 
6301 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6302 	    "st_get_density(dev = 0x%lx)\n", dev);
6303 
6304 	ASSERT(mutex_owned(ST_MUTEX));
6305 
6306 	/*
6307 	 * If Auto Density override is enabled The drive has
6308 	 * only one density and there is no point in attempting
6309 	 * find the correct one.
6310 	 *
6311 	 * Since most modern drives auto detect the density
6312 	 * and format of the recorded media before they come
6313 	 * ready. What this function does is a legacy behavior
6314 	 * and modern drives not only don't need it, The backup
6315 	 * utilities that do positioning via uscsi find the un-
6316 	 * expected rewinds problematic.
6317 	 *
6318 	 * The drives that need this are old reel to reel devices.
6319 	 * I took a swag and said they must be scsi-1 or older.
6320 	 * I don't beleave there will any of the newer devices
6321 	 * that need this. There will be some scsi-1 devices that
6322 	 * don't need this but I don't think they will be using the
6323 	 * BIG aftermarket backup and restore utilitys.
6324 	 */
6325 	if ((un->un_dp->options & ST_AUTODEN_OVERRIDE) ||
6326 	    (un->un_sd->sd_inq->inq_ansi > 1)) {
6327 		un->un_density_known = 1;
6328 		rval = 0;
6329 		goto exit;
6330 	}
6331 
6332 	/*
6333 	 * This will only work on variable record length tapes
6334 	 * if and only if all variable record length tapes autodensity
6335 	 * select.
6336 	 */
6337 	size = (unsigned)(un->un_dp->bsize ? un->un_dp->bsize : SECSIZE);
6338 	un->un_tmpbuf = kmem_alloc(size, KM_SLEEP);
6339 
6340 	/*
6341 	 * Start at the specified density
6342 	 */
6343 
6344 	dens = olddens = un->un_curdens = MT_DENSITY(un->un_dev);
6345 
6346 	for (i = 0; i < NDENSITIES; i++, ((un->un_curdens == NDENSITIES - 1) ?
6347 	    (un->un_curdens = 0) : (un->un_curdens += 1))) {
6348 		/*
6349 		 * If we've done this density before,
6350 		 * don't bother to do it again.
6351 		 */
6352 		dens = un->un_dp->densities[un->un_curdens];
6353 		if (i > 0 && dens == olddens)
6354 			continue;
6355 		olddens = dens;
6356 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6357 		    "trying density 0x%x\n", dens);
6358 		if (st_set_density(dev)) {
6359 			continue;
6360 		}
6361 
6362 		/*
6363 		 * XXX - the creates lots of headaches and slowdowns - must
6364 		 * fix.
6365 		 */
6366 		succes = (st_cmd(dev, SCMD_READ, (int)size, SYNC_CMD) == 0);
6367 		if (st_cmd(dev, SCMD_REWIND, 0, SYNC_CMD)) {
6368 			break;
6369 		}
6370 		if (succes) {
6371 			st_init(un);
6372 			rval = 0;
6373 			un->un_density_known = 1;
6374 			break;
6375 		}
6376 	}
6377 	kmem_free(un->un_tmpbuf, size);
6378 	un->un_tmpbuf = 0;
6379 
6380 exit:
6381 	ASSERT(mutex_owned(ST_MUTEX));
6382 	return (rval);
6383 }
6384 
6385 static int
6386 st_set_density(dev_t dev)
6387 {
6388 	int rval = 0;
6389 
6390 	GET_SOFT_STATE(dev);
6391 
6392 	ST_FUNC(ST_DEVINFO, st_set_density);
6393 
6394 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6395 	    "st_set_density(dev = 0x%lx): density = 0x%x\n", dev,
6396 	    un->un_dp->densities[un->un_curdens]);
6397 
6398 	ASSERT(mutex_owned(ST_MUTEX));
6399 
6400 	un->un_mspl->density = un->un_dp->densities[un->un_curdens];
6401 
6402 	if ((un->un_dp->options & ST_AUTODEN_OVERRIDE) == 0) {
6403 		/*
6404 		 * If auto density override is not set, Use mode select
6405 		 * to set density and compression.
6406 		 */
6407 		if (st_modeselect(un)) {
6408 			rval = -1;
6409 		}
6410 	} else if ((un->un_dp->options & ST_MODE_SEL_COMP) != 0) {
6411 		/*
6412 		 * If auto density and mode select compression are set,
6413 		 * This is a drive with one density code but compression
6414 		 * can be enabled or disabled.
6415 		 * Set compression but no need to set density.
6416 		 */
6417 		rval = st_set_compression(un);
6418 		if ((rval != 0) && (rval != EALREADY)) {
6419 			rval = -1;
6420 		} else {
6421 			rval = 0;
6422 		}
6423 	}
6424 
6425 	/* If sucessful set density and/or compression, mark density known */
6426 	if (rval == 0) {
6427 		un->un_density_known = 1;
6428 	}
6429 
6430 	ASSERT(mutex_owned(ST_MUTEX));
6431 	return (rval);
6432 }
6433 
6434 static int
6435 st_loadtape(dev_t dev)
6436 {
6437 	int rval;
6438 
6439 	GET_SOFT_STATE(dev);
6440 
6441 	ST_FUNC(ST_DEVINFO, st_load_tape);
6442 
6443 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6444 	    "st_loadtape(dev = 0x%lx)\n", dev);
6445 
6446 	ASSERT(mutex_owned(ST_MUTEX));
6447 
6448 	/*
6449 	 * 'LOAD' the tape to BOT by rewinding
6450 	 */
6451 	rval = st_cmd(dev, SCMD_REWIND, 1, SYNC_CMD);
6452 	if (rval == 0) {
6453 		st_init(un);
6454 		un->un_density_known = 0;
6455 	}
6456 
6457 	ASSERT(mutex_owned(ST_MUTEX));
6458 	return (rval);
6459 }
6460 
6461 
6462 /*
6463  * Note: QIC devices aren't so smart.  If you try to append
6464  * after EOM, the write can fail because the device doesn't know
6465  * it's at EOM.	 In that case, issue a read.  The read should fail
6466  * because there's no data, but the device knows it's at EOM,
6467  * so a subsequent write should succeed.  To further confuse matters,
6468  * the target returns the same error if the tape is positioned
6469  * such that a write would overwrite existing data.  That's why
6470  * we have to do the append test.  A read in the middle of
6471  * recorded data would succeed, thus indicating we're attempting
6472  * something illegal.
6473  */
6474 
6475 
6476 static void
6477 st_test_append(struct buf *bp)
6478 {
6479 	dev_t dev = bp->b_edev;
6480 	struct scsi_tape *un;
6481 	uchar_t status;
6482 	unsigned bcount;
6483 
6484 	un = ddi_get_soft_state(st_state, MTUNIT(dev));
6485 
6486 	ST_FUNC(ST_DEVINFO, st_test_append);
6487 
6488 	ASSERT(mutex_owned(ST_MUTEX));
6489 
6490 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6491 	    "st_test_append(): fileno %d\n", un->un_pos.fileno);
6492 
6493 	un->un_laststate = un->un_state;
6494 	un->un_state = ST_STATE_APPEND_TESTING;
6495 	un->un_test_append = 0;
6496 
6497 	/*
6498 	 * first, map in the buffer, because we're doing a double write --
6499 	 * first into the kernel, then onto the tape.
6500 	 */
6501 	bp_mapin(bp);
6502 
6503 	/*
6504 	 * get a copy of the data....
6505 	 */
6506 	un->un_tmpbuf = kmem_alloc((unsigned)bp->b_bcount, KM_SLEEP);
6507 	bcopy(bp->b_un.b_addr, un->un_tmpbuf, (uint_t)bp->b_bcount);
6508 
6509 	/*
6510 	 * attempt the write..
6511 	 */
6512 
6513 	if (st_cmd(dev, (int)SCMD_WRITE, (int)bp->b_bcount, SYNC_CMD) == 0) {
6514 success:
6515 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6516 		    "append write succeeded\n");
6517 		bp->b_resid = un->un_sbufp->b_resid;
6518 		mutex_exit(ST_MUTEX);
6519 		bcount = (unsigned)bp->b_bcount;
6520 		biodone(bp);
6521 		mutex_enter(ST_MUTEX);
6522 		un->un_laststate = un->un_state;
6523 		un->un_state = ST_STATE_OPEN;
6524 		kmem_free(un->un_tmpbuf, bcount);
6525 		un->un_tmpbuf = NULL;
6526 		return;
6527 	}
6528 
6529 	/*
6530 	 * The append failed. Do a short read. If that fails,  we are at EOM
6531 	 * so we can retry the write command. If that succeeds, than we're
6532 	 * all screwed up (the controller reported a real error).
6533 	 *
6534 	 * XXX: should the dummy read be > SECSIZE? should it be the device's
6535 	 * XXX: block size?
6536 	 *
6537 	 */
6538 	status = un->un_status;
6539 	un->un_status = 0;
6540 	(void) st_cmd(dev, SCMD_READ, SECSIZE, SYNC_CMD);
6541 	if (un->un_status == KEY_BLANK_CHECK) {
6542 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6543 		    "append at EOM\n");
6544 		/*
6545 		 * Okay- the read failed. We should actually have confused
6546 		 * the controller enough to allow writing. In any case, the
6547 		 * i/o is on its own from here on out.
6548 		 */
6549 		un->un_laststate = un->un_state;
6550 		un->un_state = ST_STATE_OPEN;
6551 		bcopy(bp->b_un.b_addr, un->un_tmpbuf, (uint_t)bp->b_bcount);
6552 		if (st_cmd(dev, (int)SCMD_WRITE, (int)bp->b_bcount,
6553 		    SYNC_CMD) == 0) {
6554 			goto success;
6555 		}
6556 	}
6557 
6558 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6559 	    "append write failed- not at EOM\n");
6560 	bp->b_resid = bp->b_bcount;
6561 	st_bioerror(bp, EIO);
6562 
6563 	ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6564 	    "st_test_append : EIO : append write failed - not at EOM");
6565 
6566 	/*
6567 	 * backspace one record to get back to where we were
6568 	 */
6569 	if (st_cmd(dev, SCMD_SPACE, Blk(-1), SYNC_CMD)) {
6570 		un->un_pos.pmode = invalid;
6571 	}
6572 
6573 	un->un_err_resid = bp->b_resid;
6574 	un->un_status = status;
6575 
6576 	/*
6577 	 * Note: biodone will do a bp_mapout()
6578 	 */
6579 	mutex_exit(ST_MUTEX);
6580 	bcount = (unsigned)bp->b_bcount;
6581 	biodone(bp);
6582 	mutex_enter(ST_MUTEX);
6583 	un->un_laststate = un->un_state;
6584 	un->un_state = ST_STATE_OPEN_PENDING_IO;
6585 	kmem_free(un->un_tmpbuf, bcount);
6586 	un->un_tmpbuf = NULL;
6587 }
6588 
6589 /*
6590  * Special command handler
6591  */
6592 
6593 /*
6594  * common st_cmd code. The fourth parameter states
6595  * whether the caller wishes to await the results
6596  * Note the release of the mutex during most of the function
6597  */
6598 static int
6599 st_cmd(dev_t dev, int com, int count, int wait)
6600 {
6601 	struct buf *bp;
6602 	int err;
6603 
6604 	GET_SOFT_STATE(dev);
6605 
6606 	ST_FUNC(ST_DEVINFO, st_cmd);
6607 
6608 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6609 	    "st_cmd(dev = 0x%lx, com = 0x%x, count = %x, wait = %d)\n",
6610 	    dev, com, count, wait);
6611 
6612 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
6613 	ASSERT(mutex_owned(ST_MUTEX));
6614 
6615 #ifdef STDEBUG
6616 	if ((st_debug & 0xf)) {
6617 		st_debug_cmds(un, com, count, wait);
6618 	}
6619 #endif
6620 
6621 	/* check to see if this command requires the drive to be reserved */
6622 	err = st_check_cmd_for_need_to_reserve(un, com, count);
6623 
6624 	if (err) {
6625 		return (err);
6626 	}
6627 
6628 	while (un->un_sbuf_busy)
6629 		cv_wait(&un->un_sbuf_cv, ST_MUTEX);
6630 	un->un_sbuf_busy = 1;
6631 
6632 	bp = un->un_sbufp;
6633 	bzero(bp, sizeof (buf_t));
6634 
6635 	bp->b_flags = (wait) ? B_BUSY : B_BUSY|B_ASYNC;
6636 
6637 	/*
6638 	 * Set count to the actual size of the data tranfer.
6639 	 * For commands with no data transfer, set bp->b_bcount
6640 	 * to the value to be used when constructing the
6641 	 * cdb in st_make_cmd().
6642 	 */
6643 	switch (com) {
6644 	case SCMD_READ:
6645 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6646 		    "special read %d\n", count);
6647 		bp->b_flags |= B_READ;
6648 		bp->b_un.b_addr = un->un_tmpbuf;
6649 		break;
6650 
6651 	case SCMD_WRITE:
6652 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6653 		    "special write %d\n", count);
6654 		bp->b_un.b_addr = un->un_tmpbuf;
6655 		break;
6656 
6657 	case SCMD_WRITE_FILE_MARK:
6658 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6659 		    "write %d file marks\n", count);
6660 		bp->b_bcount = count;
6661 		count = 0;
6662 		break;
6663 
6664 	case SCMD_REWIND:
6665 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "rewind\n");
6666 		bp->b_bcount = 0;
6667 		count = 0;
6668 		break;
6669 
6670 	case SCMD_SPACE:
6671 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "space\n");
6672 		/*
6673 		 * XXX The user could have entered a number that will
6674 		 * not fit in the 12 bit count field. Whats new here
6675 		 * checking that. Down the road this should use space(16).
6676 		 */
6677 		if ((SPACE_CNT(count) > 0x7fffff) ||
6678 		    (SPACE_CNT(count) < -(0x7fffff))) {
6679 			un->un_sbuf_busy = 0;
6680 			cv_signal(&un->un_sbuf_cv);
6681 			return (EINVAL);
6682 		}
6683 		bp->b_bcount = count;
6684 		count = 0;
6685 		break;
6686 
6687 	case SCMD_RESERVE:
6688 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "reserve");
6689 		bp->b_bcount = 0;
6690 		count = 0;
6691 		break;
6692 
6693 	case SCMD_RELEASE:
6694 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "release");
6695 		bp->b_bcount = 0;
6696 		count = 0;
6697 		break;
6698 
6699 	case SCMD_LOAD:
6700 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6701 		    "%s tape\n", (count & LD_LOAD) ? "load" : "unload");
6702 		bp->b_bcount = count;
6703 		count = 0;
6704 		break;
6705 
6706 	case SCMD_ERASE:
6707 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6708 		    "erase tape\n");
6709 		bp->b_bcount = 0;
6710 		count = 0;
6711 		break;
6712 
6713 	case SCMD_MODE_SENSE:
6714 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6715 		    "mode sense\n");
6716 		bp->b_flags |= B_READ;
6717 		bp->b_un.b_addr = (caddr_t)(un->un_mspl);
6718 		break;
6719 
6720 	case SCMD_MODE_SELECT:
6721 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6722 		    "mode select\n");
6723 		bp->b_un.b_addr = (caddr_t)(un->un_mspl);
6724 		break;
6725 
6726 	case SCMD_READ_BLKLIM:
6727 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6728 		    "read block limits\n");
6729 		bp->b_flags |= B_READ;
6730 		bp->b_un.b_addr = (caddr_t)(un->un_rbl);
6731 		break;
6732 
6733 	case SCMD_TEST_UNIT_READY:
6734 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6735 		    "test unit ready\n");
6736 		bp->b_bcount = 0;
6737 		count = 0;
6738 		break;
6739 
6740 	case SCMD_DOORLOCK:
6741 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6742 		    "%s tape\n", (count & MR_LOCK) ? "lock" : "unlock");
6743 		bp->b_bcount = count = 0;
6744 		break;
6745 
6746 	case SCMD_READ_POSITION:
6747 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6748 		    "read position\n");
6749 		switch (un->un_read_pos_type) {
6750 		case LONG_POS:
6751 			count = sizeof (tape_position_long_t);
6752 			break;
6753 		case EXT_POS:
6754 			count = min(count, sizeof (tape_position_ext_t));
6755 			break;
6756 		case SHORT_POS:
6757 			count = sizeof (tape_position_t);
6758 			break;
6759 		default:
6760 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
6761 			    "Unknown read position type 0x%x in "
6762 			    "st_make_cmd()\n", un->un_read_pos_type);
6763 		}
6764 		bp->b_bcount = count;
6765 		bp->b_flags |= B_READ;
6766 		bp->b_un.b_addr = (caddr_t)un->un_read_pos_data;
6767 		break;
6768 
6769 	default:
6770 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
6771 		    "Unhandled scsi command 0x%x in st_cmd()\n", com);
6772 	}
6773 
6774 	mutex_exit(ST_MUTEX);
6775 
6776 	if (count > 0) {
6777 		/*
6778 		 * We're going to do actual I/O.
6779 		 * Set things up for physio.
6780 		 */
6781 		struct iovec aiov;
6782 		struct uio auio;
6783 		struct uio *uio = &auio;
6784 
6785 		bzero(&auio, sizeof (struct uio));
6786 		bzero(&aiov, sizeof (struct iovec));
6787 		aiov.iov_base = bp->b_un.b_addr;
6788 		aiov.iov_len = count;
6789 
6790 		uio->uio_iov = &aiov;
6791 		uio->uio_iovcnt = 1;
6792 		uio->uio_resid = aiov.iov_len;
6793 		uio->uio_segflg = UIO_SYSSPACE;
6794 
6795 		/*
6796 		 * Let physio do the rest...
6797 		 */
6798 		bp->b_forw = (struct buf *)(uintptr_t)com;
6799 		bp->b_back = NULL;
6800 		err = physio(st_strategy, bp, dev,
6801 		    (bp->b_flags & B_READ) ? B_READ : B_WRITE,
6802 		    st_minphys, uio);
6803 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6804 		    "st_cmd: physio returns %d\n", err);
6805 	} else {
6806 		/*
6807 		 * Mimic physio
6808 		 */
6809 		bp->b_forw = (struct buf *)(uintptr_t)com;
6810 		bp->b_back = NULL;
6811 		bp->b_edev = dev;
6812 		bp->b_dev = cmpdev(dev);
6813 		bp->b_blkno = 0;
6814 		bp->b_resid = 0;
6815 		(void) st_strategy(bp);
6816 		if (!wait) {
6817 			/*
6818 			 * This is an async command- the caller won't wait
6819 			 * and doesn't care about errors.
6820 			 */
6821 			mutex_enter(ST_MUTEX);
6822 			return (0);
6823 		}
6824 
6825 		/*
6826 		 * BugTraq #4260046
6827 		 * ----------------
6828 		 * Restore Solaris 2.5.1 behavior, namely call biowait
6829 		 * unconditionally. The old comment said...
6830 		 *
6831 		 * "if strategy was flagged with  persistent errors, we would
6832 		 *  have an error here, and the bp would never be sent, so we
6833 		 *  don't want to wait on a bp that was never sent...or hang"
6834 		 *
6835 		 * The new rationale, courtesy of Chitrank...
6836 		 *
6837 		 * "we should unconditionally biowait() here because
6838 		 *  st_strategy() will do a biodone() in the persistent error
6839 		 *  case and the following biowait() will return immediately.
6840 		 *  If not, in the case of "errors after pkt alloc" in
6841 		 *  st_start(), we will not biowait here which will cause the
6842 		 *  next biowait() to return immediately which will cause
6843 		 *  us to send out the next command. In the case where both of
6844 		 *  these use the sbuf, when the first command completes we'll
6845 		 *  free the packet attached to sbuf and the same pkt will
6846 		 *  get freed again when we complete the second command.
6847 		 *  see esc 518987.  BTW, it is necessary to do biodone() in
6848 		 *  st_start() for the pkt alloc failure case because physio()
6849 		 *  does biowait() and will hang if we don't do biodone()"
6850 		 */
6851 
6852 		err = biowait(bp);
6853 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6854 		    "st_cmd: biowait returns %d\n", err);
6855 	}
6856 	mutex_enter(ST_MUTEX);
6857 
6858 	un->un_sbuf_busy = 0;
6859 
6860 	/*
6861 	 * If was a space command need to update logical block position.
6862 	 * If the command failed such that positioning is invalid, Don't
6863 	 * update the position as the user must do this to validate the
6864 	 * position for data protection.
6865 	 */
6866 	if ((com == SCMD_SPACE) && (un->un_pos.pmode != invalid)) {
6867 		uchar_t status = un->un_status;
6868 		(void) st_update_block_pos(un);
6869 		un->un_status = status;
6870 	}
6871 
6872 	cv_signal(&un->un_sbuf_cv);
6873 	return (err);
6874 }
6875 
6876 static int
6877 st_set_compression(struct scsi_tape *un)
6878 {
6879 	int rval;
6880 	int turn_compression_on;
6881 	minor_t minor;
6882 
6883 	ST_FUNC(ST_DEVINFO, st_set_compression);
6884 
6885 	/*
6886 	 * Drive either dosn't have compression or it is controlled with
6887 	 * special density codes. Return ENOTTY so caller
6888 	 * knows nothing was done.
6889 	 */
6890 	if ((un->un_dp->options & ST_MODE_SEL_COMP) == 0) {
6891 		un->un_comp_page = 0;
6892 		return (ENOTTY);
6893 	}
6894 
6895 	/* set compression based on minor node opened */
6896 	minor = MT_DENSITY(un->un_dev);
6897 
6898 	/*
6899 	 * If this the compression density or
6900 	 * the drive has two densities and uses mode select for
6901 	 * control of compression turn on compression for MT_DENSITY2
6902 	 * as well.
6903 	 */
6904 	if ((minor == ST_COMPRESSION_DENSITY) ||
6905 	    (minor == MT_DENSITY(MT_DENSITY2)) &&
6906 	    (un->un_dp->densities[0] == un->un_dp->densities[1]) &&
6907 	    (un->un_dp->densities[2] == un->un_dp->densities[3]) &&
6908 	    (un->un_dp->densities[0] != un->un_dp->densities[2])) {
6909 
6910 		turn_compression_on = 1;
6911 	} else {
6912 		turn_compression_on = 0;
6913 	}
6914 
6915 	un->un_mspl->high_bl = (uchar_t)(un->un_bsize >> 16);
6916 	un->un_mspl->mid_bl  = (uchar_t)(un->un_bsize >> 8);
6917 	un->un_mspl->low_bl  = (uchar_t)(un->un_bsize);
6918 
6919 	/*
6920 	 * Need to determine which page does the device use for compression.
6921 	 * First try the data compression page. If this fails try the device
6922 	 * configuration page
6923 	 */
6924 
6925 	if ((un->un_comp_page & ST_DEV_DATACOMP_PAGE) == ST_DEV_DATACOMP_PAGE) {
6926 		rval = st_set_datacomp_page(un, turn_compression_on);
6927 		if (rval == EALREADY) {
6928 			return (rval);
6929 		}
6930 		if (rval != 0) {
6931 			if (un->un_status == KEY_ILLEGAL_REQUEST) {
6932 				/*
6933 				 * This device does not support data
6934 				 * compression page
6935 				 */
6936 				un->un_comp_page = ST_DEV_CONFIG_PAGE;
6937 			} else if (un->un_state >= ST_STATE_OPEN) {
6938 				un->un_pos.pmode = invalid;
6939 				rval = EIO;
6940 			} else {
6941 				rval = -1;
6942 			}
6943 		} else {
6944 			un->un_comp_page = ST_DEV_DATACOMP_PAGE;
6945 		}
6946 	}
6947 
6948 	if ((un->un_comp_page & ST_DEV_CONFIG_PAGE) == ST_DEV_CONFIG_PAGE) {
6949 		rval = st_set_devconfig_page(un, turn_compression_on);
6950 		if (rval == EALREADY) {
6951 			return (rval);
6952 		}
6953 		if (rval != 0) {
6954 			if (un->un_status == KEY_ILLEGAL_REQUEST) {
6955 				/*
6956 				 * This device does not support
6957 				 * compression at all advice the
6958 				 * user and unset ST_MODE_SEL_COMP
6959 				 */
6960 				un->un_dp->options &= ~ST_MODE_SEL_COMP;
6961 				un->un_comp_page = 0;
6962 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
6963 				    "Device Does Not Support Compression\n");
6964 			} else if (un->un_state >= ST_STATE_OPEN) {
6965 				un->un_pos.pmode = invalid;
6966 				rval = EIO;
6967 			} else {
6968 				rval = -1;
6969 			}
6970 		}
6971 	}
6972 
6973 	return (rval);
6974 }
6975 
6976 /*
6977  * set or unset compression thru device configuration page.
6978  */
6979 static int
6980 st_set_devconfig_page(struct scsi_tape *un, int compression_on)
6981 {
6982 	unsigned char cflag;
6983 	int rval = 0;
6984 
6985 
6986 	ST_FUNC(ST_DEVINFO, st_set_devconfig_page);
6987 
6988 	ASSERT(mutex_owned(ST_MUTEX));
6989 	/*
6990 	 * Figure what to set compression flag to.
6991 	 */
6992 	if (compression_on) {
6993 		/* They have selected a compression node */
6994 		if (un->un_dp->type == ST_TYPE_FUJI) {
6995 			cflag = 0x84;   /* use EDRC */
6996 		} else {
6997 			cflag = ST_DEV_CONFIG_DEF_COMP;
6998 		}
6999 	} else {
7000 		cflag = ST_DEV_CONFIG_NO_COMP;
7001 	}
7002 
7003 	/*
7004 	 * If compression is already set the way it was requested.
7005 	 * And if this not the first time we has tried.
7006 	 */
7007 	if ((cflag == un->un_mspl->page.dev.comp_alg) &&
7008 	    (un->un_comp_page == ST_DEV_DATACOMP_PAGE)) {
7009 		return (EALREADY);
7010 	}
7011 
7012 	un->un_mspl->page.dev.comp_alg = cflag;
7013 	/*
7014 	 * need to send mode select even if correct compression is
7015 	 * already set since need to set density code
7016 	 */
7017 
7018 #ifdef STDEBUG
7019 	if ((st_debug & 0xf) >= 6) {
7020 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
7021 		    "st_set_devconfig_page: sense data for mode select",
7022 		    (char *)un->un_mspl, sizeof (struct seq_mode));
7023 	}
7024 #endif
7025 	rval = st_gen_mode_select(un, un->un_mspl, sizeof (struct seq_mode));
7026 
7027 	return (rval);
7028 }
7029 
7030 /*
7031  * set/reset compression bit thru data compression page
7032  */
7033 static int
7034 st_set_datacomp_page(struct scsi_tape *un, int compression_on)
7035 {
7036 	int compression_on_already;
7037 	int rval = 0;
7038 
7039 
7040 	ST_FUNC(ST_DEVINFO, st_set_datacomp_page);
7041 
7042 	ASSERT(mutex_owned(ST_MUTEX));
7043 	/*
7044 	 * If drive is not capable of compression (at this time)
7045 	 * return EALREADY so caller doesn't think that this page
7046 	 * is not supported. This check is for drives that can
7047 	 * disable compression from the front panel or configuration.
7048 	 * I doubt that a drive that supports this page is not really
7049 	 * capable of compression.
7050 	 */
7051 	if (un->un_mspl->page.comp.dcc == 0) {
7052 		return (EALREADY);
7053 	}
7054 
7055 	/* See if compression currently turned on */
7056 	if (un->un_mspl->page.comp.dce) {
7057 		compression_on_already = 1;
7058 	} else {
7059 		compression_on_already = 0;
7060 	}
7061 
7062 	/*
7063 	 * If compression is already set the way it was requested.
7064 	 * And if this not the first time we has tried.
7065 	 */
7066 	if ((compression_on == compression_on_already) &&
7067 	    (un->un_comp_page == ST_DEV_DATACOMP_PAGE)) {
7068 		return (EALREADY);
7069 	}
7070 
7071 	/*
7072 	 * if we are already set to the appropriate compression
7073 	 * mode, don't set it again
7074 	 */
7075 	if (compression_on) {
7076 		/* compression selected */
7077 		un->un_mspl->page.comp.dce = 1;
7078 	} else {
7079 		un->un_mspl->page.comp.dce = 0;
7080 	}
7081 
7082 
7083 #ifdef STDEBUG
7084 	if ((st_debug & 0xf) >= 6) {
7085 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
7086 		    "st_set_datacomp_page: sense data for mode select",
7087 		    (char *)un->un_mspl, sizeof (struct seq_mode));
7088 	}
7089 #endif
7090 	rval = st_gen_mode_select(un, un->un_mspl, sizeof (struct seq_mode));
7091 
7092 	return (rval);
7093 }
7094 
7095 static int
7096 st_modesense(struct scsi_tape *un)
7097 {
7098 	int rval;
7099 	uchar_t page;
7100 
7101 	ST_FUNC(ST_DEVINFO, st_modesense);
7102 
7103 	page = un->un_comp_page;
7104 
7105 	switch (page) {
7106 	case ST_DEV_DATACOMP_PAGE:
7107 	case ST_DEV_CONFIG_PAGE: /* fall through */
7108 		rval = st_gen_mode_sense(un, page, un->un_mspl,
7109 		    sizeof (struct seq_mode));
7110 		break;
7111 
7112 	case ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE:
7113 		if (un->un_dp->options & ST_MODE_SEL_COMP) {
7114 			page = ST_DEV_DATACOMP_PAGE;
7115 			rval = st_gen_mode_sense(un, page, un->un_mspl,
7116 			    sizeof (struct seq_mode));
7117 			if (rval == 0 && un->un_mspl->page_code == page) {
7118 				un->un_comp_page = page;
7119 				break;
7120 			}
7121 			page = ST_DEV_CONFIG_PAGE;
7122 			rval = st_gen_mode_sense(un, page, un->un_mspl,
7123 			    sizeof (struct seq_mode));
7124 			if (rval == 0 && un->un_mspl->page_code == page) {
7125 				un->un_comp_page = page;
7126 				break;
7127 			}
7128 			un->un_dp->options &= ~ST_MODE_SEL_COMP;
7129 			un->un_comp_page = 0;
7130 		} else {
7131 			un->un_comp_page = 0;
7132 		}
7133 
7134 	default:	/* fall through */
7135 		rval = st_cmd(un->un_dev, SCMD_MODE_SENSE, MSIZE, SYNC_CMD);
7136 	}
7137 	return (rval);
7138 }
7139 
7140 static int
7141 st_modeselect(struct scsi_tape *un)
7142 {
7143 	int rval = 0;
7144 	int ix;
7145 
7146 	ST_FUNC(ST_DEVINFO, st_modeselect);
7147 
7148 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7149 	    "st_modeselect(dev = 0x%lx): density = 0x%x\n",
7150 	    un->un_dev, un->un_mspl->density);
7151 
7152 	ASSERT(mutex_owned(ST_MUTEX));
7153 
7154 	/*
7155 	 * The parameter list should be the same for all of the
7156 	 * cases that follow so set them here
7157 	 *
7158 	 * Try mode select first if if fails set fields manually
7159 	 */
7160 	rval = st_modesense(un);
7161 	if (rval != 0) {
7162 		ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
7163 		    "st_modeselect: First mode sense failed\n");
7164 		un->un_mspl->bd_len  = 8;
7165 		un->un_mspl->high_nb = 0;
7166 		un->un_mspl->mid_nb  = 0;
7167 		un->un_mspl->low_nb  = 0;
7168 	}
7169 	un->un_mspl->high_bl = (uchar_t)(un->un_bsize >> 16);
7170 	un->un_mspl->mid_bl  = (uchar_t)(un->un_bsize >> 8);
7171 	un->un_mspl->low_bl  = (uchar_t)(un->un_bsize);
7172 
7173 
7174 	/*
7175 	 * If configured to use a specific density code for a media type.
7176 	 * curdens is previously set by the minor node opened.
7177 	 * If the media type doesn't match the minor node we change it so it
7178 	 * looks like the correct one was opened.
7179 	 */
7180 	if (un->un_dp->options & ST_KNOWS_MEDIA) {
7181 		uchar_t best;
7182 
7183 		for (best = 0xff, ix = 0; ix < NDENSITIES; ix++) {
7184 			if (un->un_mspl->media_type ==
7185 			    un->un_dp->mediatype[ix]) {
7186 				best = ix;
7187 				/*
7188 				 * It matches but it might not be the only one.
7189 				 * Use the highest matching media type but not
7190 				 * to exceed the density selected by the open.
7191 				 */
7192 				if (ix < un->un_curdens) {
7193 					continue;
7194 				}
7195 				un->un_curdens = ix;
7196 				break;
7197 			}
7198 		}
7199 		/* If a match was found best will not be 0xff any more */
7200 		if (best < NDENSITIES) {
7201 			ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
7202 			    "found media 0x%X using density 0x%X\n",
7203 			    un->un_mspl->media_type,
7204 			    un->un_dp->densities[best]);
7205 			un->un_mspl->density = un->un_dp->densities[best];
7206 		} else {
7207 			/* Otherwise set density based on minor node opened */
7208 			un->un_mspl->density =
7209 			    un->un_dp->densities[un->un_curdens];
7210 		}
7211 	} else {
7212 		un->un_mspl->density = un->un_dp->densities[un->un_curdens];
7213 	}
7214 
7215 	if (un->un_dp->options & ST_NOBUF) {
7216 		un->un_mspl->bufm = 0;
7217 	} else {
7218 		un->un_mspl->bufm = 1;
7219 	}
7220 
7221 	rval = st_set_compression(un);
7222 
7223 	/*
7224 	 * If st_set_compression returned invalid or already it
7225 	 * found no need to do the mode select.
7226 	 * So do it here.
7227 	 */
7228 	if ((rval == ENOTTY) || (rval == EALREADY)) {
7229 
7230 		/* Zero non-writeable fields */
7231 		un->un_mspl->data_len = 0;
7232 		un->un_mspl->media_type = 0;
7233 		un->un_mspl->wp = 0;
7234 
7235 		/* need to set the density code */
7236 		rval = st_cmd(un->un_dev, SCMD_MODE_SELECT, MSIZE, SYNC_CMD);
7237 		if (rval != 0) {
7238 			if (un->un_state >= ST_STATE_OPEN) {
7239 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
7240 				    "unable to set tape mode\n");
7241 				un->un_pos.pmode = invalid;
7242 				rval = EIO;
7243 			} else {
7244 				rval = -1;
7245 			}
7246 		}
7247 	}
7248 
7249 	/*
7250 	 * The spec recommends to send a mode sense after a mode select
7251 	 */
7252 	(void) st_modesense(un);
7253 
7254 	ASSERT(mutex_owned(ST_MUTEX));
7255 
7256 	return (rval);
7257 }
7258 
7259 /*
7260  * st_gen_mode_sense
7261  *
7262  * generic mode sense.. it allows for any page
7263  */
7264 static int
7265 st_gen_mode_sense(struct scsi_tape *un, int page, struct seq_mode *page_data,
7266     int page_size)
7267 {
7268 
7269 	int r;
7270 	char	cdb[CDB_GROUP0];
7271 	struct uscsi_cmd *com;
7272 
7273 	ST_FUNC(ST_DEVINFO, st_gen_mode_sense);
7274 
7275 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
7276 
7277 	bzero(cdb, CDB_GROUP0);
7278 	cdb[0] = SCMD_MODE_SENSE;
7279 	cdb[2] = (char)page;
7280 	cdb[4] = (char)page_size;
7281 
7282 	com->uscsi_cdb = cdb;
7283 	com->uscsi_cdblen = CDB_GROUP0;
7284 	com->uscsi_bufaddr = (caddr_t)page_data;
7285 	com->uscsi_buflen = page_size;
7286 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
7287 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
7288 
7289 	r = st_ioctl_cmd(un->un_dev, com, FKIOCTL);
7290 	kmem_free(com, sizeof (*com));
7291 	return (r);
7292 }
7293 
7294 /*
7295  * st_gen_mode_select
7296  *
7297  * generic mode select.. it allows for any page
7298  */
7299 static int
7300 st_gen_mode_select(struct scsi_tape *un, struct seq_mode *page_data,
7301     int page_size)
7302 {
7303 
7304 	int r;
7305 	char cdb[CDB_GROUP0];
7306 	struct uscsi_cmd *com;
7307 
7308 	ST_FUNC(ST_DEVINFO, st_gen_mode_select);
7309 
7310 	/* Zero non-writeable fields */
7311 	page_data->data_len = 0;
7312 	page_data->media_type = 0;
7313 	page_data->wp = 0;
7314 
7315 	/*
7316 	 * If mode select has any page data, zero the ps (Page Savable) bit.
7317 	 */
7318 	if (page_size > MSIZE) {
7319 		page_data->ps = 0;
7320 	}
7321 
7322 
7323 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
7324 
7325 	/*
7326 	 * then, do a mode select to set what ever info
7327 	 */
7328 	bzero(cdb, CDB_GROUP0);
7329 	cdb[0] = SCMD_MODE_SELECT;
7330 	cdb[1] = 0x10;		/* set PF bit for many third party drives */
7331 	cdb[4] = (char)page_size;
7332 
7333 	com->uscsi_cdb = cdb;
7334 	com->uscsi_cdblen = CDB_GROUP0;
7335 	com->uscsi_bufaddr = (caddr_t)page_data;
7336 	com->uscsi_buflen = page_size;
7337 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
7338 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_WRITE;
7339 
7340 	r = st_ioctl_cmd(un->un_dev, com, FKIOCTL);
7341 
7342 	kmem_free(com, sizeof (*com));
7343 	return (r);
7344 }
7345 
7346 /*
7347  * Changes devices blocksize and bsize to requested blocksize nblksz.
7348  * Returns returned value from first failed call or zero on success.
7349  */
7350 static int
7351 st_change_block_size(dev_t dev, uint32_t nblksz)
7352 {
7353 	struct seq_mode *current;
7354 	int rval;
7355 	uint32_t oldblksz;
7356 
7357 	GET_SOFT_STATE(dev);
7358 
7359 	ST_FUNC(ST_DEVINFO, st_change_block_size);
7360 
7361 	current = kmem_zalloc(MSIZE, KM_SLEEP);
7362 
7363 	/* Read current settings */
7364 	rval = st_gen_mode_sense(un, 0, current, MSIZE);
7365 	if (rval != 0) {
7366 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
7367 		    "mode sense for change block size failed: rval = %d", rval);
7368 		goto finish;
7369 	}
7370 
7371 	/* Figure the current block size */
7372 	oldblksz =
7373 	    (current->high_bl << 16) |
7374 	    (current->mid_bl << 8) |
7375 	    (current->low_bl);
7376 
7377 	/* If current block size is the same as requested were done */
7378 	if (oldblksz == nblksz) {
7379 		un->un_bsize = nblksz;
7380 		rval = 0;
7381 		goto finish;
7382 	}
7383 
7384 	/* Change to requested block size */
7385 	current->high_bl = (uchar_t)(nblksz >> 16);
7386 	current->mid_bl  = (uchar_t)(nblksz >> 8);
7387 	current->low_bl  = (uchar_t)(nblksz);
7388 
7389 	/* Attempt to change block size */
7390 	rval = st_gen_mode_select(un, current, MSIZE);
7391 	if (rval != 0) {
7392 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
7393 		    "Set new block size failed: rval = %d", rval);
7394 		goto finish;
7395 	}
7396 
7397 	/* Read back and verify setting */
7398 	rval = st_modesense(un);
7399 	if (rval == 0) {
7400 		un->un_bsize =
7401 		    (un->un_mspl->high_bl << 16) |
7402 		    (un->un_mspl->mid_bl << 8) |
7403 		    (un->un_mspl->low_bl);
7404 
7405 		if (un->un_bsize != nblksz) {
7406 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
7407 			    "Blocksize set does not equal requested blocksize"
7408 			    "(read: %u requested: %u)\n", nblksz, un->un_bsize);
7409 			rval = EIO;
7410 		}
7411 	}
7412 finish:
7413 	kmem_free(current, MSIZE);
7414 	return (rval);
7415 }
7416 
7417 
7418 static void
7419 st_init(struct scsi_tape *un)
7420 {
7421 	ST_FUNC(ST_DEVINFO, st_init);
7422 
7423 	ASSERT(mutex_owned(ST_MUTEX));
7424 
7425 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7426 	    "st_init(): dev = 0x%lx, will reset fileno, blkno, eof\n",
7427 	    un->un_dev);
7428 
7429 	un->un_pos.blkno = 0;
7430 	un->un_pos.fileno = 0;
7431 	un->un_lastop = ST_OP_NIL;
7432 	un->un_pos.eof = ST_NO_EOF;
7433 	un->un_pwr_mgmt = ST_PWR_NORMAL;
7434 	if (st_error_level != SCSI_ERR_ALL) {
7435 		if (DEBUGGING) {
7436 			st_error_level = SCSI_ERR_ALL;
7437 		} else {
7438 			st_error_level = SCSI_ERR_RETRYABLE;
7439 		}
7440 	}
7441 }
7442 
7443 
7444 static void
7445 st_make_cmd(struct scsi_tape *un, struct buf *bp, int (*func)(caddr_t))
7446 {
7447 	struct scsi_pkt *pkt;
7448 	struct uscsi_cmd *ucmd;
7449 	int count, tval = 0;
7450 	uint_t addr = 0;
7451 	int flags = 0;
7452 	int cdb_len = CDB_GROUP0; /* default */
7453 	uchar_t com;
7454 	char fixbit;
7455 
7456 	ST_FUNC(ST_DEVINFO, st_make_cmd);
7457 
7458 	ASSERT(mutex_owned(ST_MUTEX));
7459 
7460 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7461 	    "st_make_cmd(): dev = 0x%lx\n", un->un_dev);
7462 
7463 
7464 	/*
7465 	 * fixbit is for setting the Fixed Mode and Suppress Incorrect
7466 	 * Length Indicator bits on read/write commands, for setting
7467 	 * the Long bit on erase commands, and for setting the Code
7468 	 * Field bits on space commands.
7469 	 * XXX why do we set lastop here?
7470 	 */
7471 
7472 	if (bp != un->un_sbufp) {		/* regular raw I/O */
7473 		int stat_size = (un->un_arq_enabled ?
7474 		    sizeof (struct scsi_arq_status) : 1);
7475 		pkt = scsi_init_pkt(ROUTE, NULL, bp,
7476 		    CDB_GROUP0, stat_size, 0, 0, func, (caddr_t)un);
7477 		if (pkt == NULL) {
7478 			goto exit;
7479 		}
7480 		SET_BP_PKT(bp, pkt);
7481 		if (un->un_bsize == 0) {
7482 			count = bp->b_bcount;
7483 			fixbit = 0;
7484 		} else {
7485 			count = bp->b_bcount / un->un_bsize;
7486 			fixbit = 1;
7487 		}
7488 		if (bp->b_flags & B_READ) {
7489 			com = SCMD_READ;
7490 			un->un_lastop = ST_OP_READ;
7491 			if ((un->un_bsize == 0) && /* Not Fixed Block */
7492 			    (un->un_dp->options & ST_READ_IGNORE_ILI)) {
7493 				fixbit = 2;
7494 			}
7495 		} else {
7496 			com = SCMD_WRITE;
7497 			un->un_lastop = ST_OP_WRITE;
7498 		}
7499 
7500 		tval = un->un_dp->io_timeout;
7501 
7502 		/*
7503 		 * For really large xfers, increase timeout
7504 		 */
7505 		if (bp->b_bcount > (10 * ONE_MEG))
7506 			tval *= bp->b_bcount/(10 * ONE_MEG);
7507 
7508 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7509 		    "%s %d amt 0x%lx\n", (com == SCMD_WRITE) ?
7510 		    wr_str: rd_str, un->un_pos.blkno, bp->b_bcount);
7511 
7512 	} else if ((ucmd = BP_UCMD(bp)) != NULL) {
7513 		/*
7514 		 * uscsi - build command, allocate scsi resources
7515 		 */
7516 		st_make_uscsi_cmd(un, ucmd, bp, func);
7517 		goto exit;
7518 
7519 	} else {				/* special I/O */
7520 		int stat_size = (un->un_arq_enabled ?
7521 		    sizeof (struct scsi_arq_status) : 1);
7522 		struct buf *allocbp = NULL;
7523 		com = (uchar_t)(uintptr_t)bp->b_forw;
7524 		count = bp->b_bcount;
7525 
7526 		switch (com) {
7527 		case SCMD_READ:
7528 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7529 			    "special read %d\n", count);
7530 			if (un->un_bsize == 0) {
7531 				fixbit = 2;	/* suppress SILI */
7532 			} else {
7533 				fixbit = 1;	/* Fixed Block Mode */
7534 				count /= un->un_bsize;
7535 			}
7536 			allocbp = bp;
7537 			un->un_lastop = ST_OP_READ;
7538 			tval = un->un_dp->io_timeout;
7539 			break;
7540 
7541 		case SCMD_WRITE:
7542 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7543 			    "special write %d\n", count);
7544 			if (un->un_bsize != 0) {
7545 				fixbit = 1;	/* Fixed Block Mode */
7546 				count /= un->un_bsize;
7547 			} else {
7548 				fixbit = 0;
7549 			}
7550 			allocbp = bp;
7551 			un->un_lastop = ST_OP_WRITE;
7552 			tval = un->un_dp->io_timeout;
7553 			break;
7554 
7555 		case SCMD_WRITE_FILE_MARK:
7556 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7557 			    "write %d file marks\n", count);
7558 			un->un_lastop = ST_OP_WEOF;
7559 			fixbit = 0;
7560 			tval = un->un_dp->io_timeout;
7561 			break;
7562 
7563 		case SCMD_REWIND:
7564 			if (bp->b_flags & B_ASYNC) {
7565 				fixbit = 1;
7566 			} else {
7567 				fixbit = 0;
7568 			}
7569 			count = 0;
7570 			un->un_lastop = ST_OP_CTL;
7571 			tval = un->un_dp->rewind_timeout;
7572 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7573 			    "rewind\n");
7574 			break;
7575 
7576 		case SCMD_SPACE:
7577 			fixbit = SPACE_TYPE(count);
7578 			count = (int)SPACE_CNT(count);
7579 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7580 			    "space %s %d from file %d blk %d\n",
7581 			    space_strs[fixbit & 7], count,
7582 			    un->un_pos.fileno, un->un_pos.blkno);
7583 			un->un_lastop = ST_OP_CTL;
7584 			tval = un->un_dp->space_timeout;
7585 			break;
7586 
7587 		case SCMD_LOAD:
7588 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7589 			    "%s tape\n", (count & LD_LOAD) ? "load" : "unload");
7590 			fixbit = 0;
7591 
7592 			/* Loading or Unloading */
7593 			if (count & LD_LOAD) {
7594 				tval = un->un_dp->load_timeout;
7595 			} else {
7596 				tval = un->un_dp->unload_timeout;
7597 			}
7598 			/* Is Retension requested */
7599 			if (count & LD_RETEN) {
7600 				tval += un->un_dp->rewind_timeout;
7601 			}
7602 			un->un_lastop = ST_OP_CTL;
7603 			break;
7604 
7605 		case SCMD_ERASE:
7606 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7607 			    "erase tape\n");
7608 			count = 0;
7609 			/*
7610 			 * We support long erase only
7611 			 */
7612 			fixbit = 1;
7613 			tval = un->un_dp->erase_timeout;
7614 			un->un_lastop = ST_OP_CTL;
7615 			break;
7616 
7617 		case SCMD_MODE_SENSE:
7618 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7619 			    "mode sense\n");
7620 			allocbp = bp;
7621 			fixbit = 0;
7622 			tval = un->un_dp->non_motion_timeout;
7623 			un->un_lastop = ST_OP_CTL;
7624 			break;
7625 
7626 		case SCMD_MODE_SELECT:
7627 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7628 			    "mode select\n");
7629 			allocbp = bp;
7630 			fixbit = 0;
7631 			tval = un->un_dp->non_motion_timeout;
7632 			un->un_lastop = ST_OP_CTL;
7633 			break;
7634 
7635 		case SCMD_RESERVE:
7636 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7637 			    "reserve\n");
7638 			fixbit = 0;
7639 			tval = un->un_dp->non_motion_timeout;
7640 			un->un_lastop = ST_OP_CTL;
7641 			break;
7642 
7643 		case SCMD_RELEASE:
7644 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7645 			    "release\n");
7646 			fixbit = 0;
7647 			tval = un->un_dp->non_motion_timeout;
7648 			un->un_lastop = ST_OP_CTL;
7649 			break;
7650 
7651 		case SCMD_READ_BLKLIM:
7652 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7653 			    "read block limits\n");
7654 			allocbp = bp;
7655 			fixbit = count = 0;
7656 			tval = un->un_dp->non_motion_timeout;
7657 			un->un_lastop = ST_OP_CTL;
7658 			break;
7659 
7660 		case SCMD_TEST_UNIT_READY:
7661 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7662 			    "test unit ready\n");
7663 			fixbit = 0;
7664 			tval = un->un_dp->non_motion_timeout;
7665 			un->un_lastop = ST_OP_CTL;
7666 			break;
7667 
7668 		case SCMD_DOORLOCK:
7669 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7670 			    "prevent/allow media removal\n");
7671 			fixbit = 0;
7672 			tval = un->un_dp->non_motion_timeout;
7673 			un->un_lastop = ST_OP_CTL;
7674 			break;
7675 
7676 		case SCMD_READ_POSITION:
7677 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7678 			    "read position\n");
7679 			fixbit = un->un_read_pos_type;
7680 			cdb_len = CDB_GROUP1;
7681 			tval = un->un_dp->non_motion_timeout;
7682 			allocbp = bp;
7683 			un->un_lastop = ST_OP_CTL;
7684 			switch (un->un_read_pos_type) {
7685 			case LONG_POS:
7686 				count = 0;
7687 				break;
7688 			case EXT_POS:
7689 				count = sizeof (tape_position_ext_t);
7690 				break;
7691 			case SHORT_POS:
7692 				count = 0;
7693 				break;
7694 			default:
7695 				ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
7696 				    "Unknown read position type 0x%x in "
7697 				    " st_make_cmd()\n", un->un_read_pos_type);
7698 			}
7699 			break;
7700 
7701 		default:
7702 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
7703 			    "Unhandled scsi command 0x%x in st_make_cmd()\n",
7704 			    com);
7705 		}
7706 		pkt = scsi_init_pkt(ROUTE, NULL, allocbp, cdb_len, stat_size,
7707 		    0, 0, func, (caddr_t)un);
7708 		if (pkt == NULL) {
7709 			goto exit;
7710 		}
7711 		if (allocbp) {
7712 			ASSERT(geterror(allocbp) == 0);
7713 		}
7714 
7715 	}
7716 
7717 
7718 	(void) scsi_setup_cdb((union scsi_cdb *)pkt->pkt_cdbp,
7719 	    com, addr, (uint_t)count, 0);
7720 	FILL_SCSI1_LUN(un->un_sd, pkt);
7721 	/*
7722 	 * Initialize the SILI/Fixed bits of the byte 1 of cdb.
7723 	 */
7724 	((union scsi_cdb *)(pkt->pkt_cdbp))->t_code = fixbit;
7725 	pkt->pkt_flags = flags;
7726 
7727 #ifdef STDEBUG
7728 	if ((st_debug & 0xf) >= 6) {
7729 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
7730 		    "cmd cdb", (char *)pkt->pkt_cdbp, cdb_len);
7731 	}
7732 #endif
7733 
7734 	/*
7735 	 * If ST_SHORT_FILEMARKS bit is ON for EXABYTE
7736 	 * device, set the Vendor Unique bit to
7737 	 * write Short File Mark.
7738 	 */
7739 	if (com == SCMD_WRITE_FILE_MARK &&
7740 	    un->un_dp->options & ST_SHORT_FILEMARKS) {
7741 		switch (un->un_dp->type) {
7742 		case ST_TYPE_EXB8500:
7743 		case ST_TYPE_EXABYTE:
7744 			/*
7745 			 * Now the Vendor Unique bit 7 in Byte 5 of CDB
7746 			 * is set to to write Short File Mark
7747 			 */
7748 			((union scsi_cdb *)pkt->pkt_cdbp)->g0_vu_1 = 1;
7749 			break;
7750 
7751 		default:
7752 			/*
7753 			 * Well, if ST_SHORT_FILEMARKS is set for other
7754 			 * tape drives, it is just ignored
7755 			 */
7756 			break;
7757 		}
7758 	}
7759 	ASSERT(tval);
7760 	pkt->pkt_time = tval;
7761 	pkt->pkt_comp = st_intr;
7762 	pkt->pkt_private = (opaque_t)bp;
7763 
7764 	SET_BP_PKT(bp, pkt);
7765 
7766 exit:
7767 	ASSERT(mutex_owned(ST_MUTEX));
7768 }
7769 
7770 
7771 /*
7772  * Build a command based on a uscsi command;
7773  */
7774 static void
7775 st_make_uscsi_cmd(struct scsi_tape *un, struct uscsi_cmd *ucmd,
7776     struct buf *bp, int (*func)(caddr_t))
7777 {
7778 	struct scsi_pkt *pkt;
7779 	caddr_t cdb;
7780 	int	cdblen;
7781 	int stat_size;
7782 
7783 	ST_FUNC(ST_DEVINFO, st_make_uscsi_cmd);
7784 
7785 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7786 	    "st_make_uscsi_cmd(): dev = 0x%lx\n", un->un_dev);
7787 
7788 	if (ucmd->uscsi_flags & USCSI_RQENABLE) {
7789 		stat_size = (un->un_arq_enabled ?
7790 		    sizeof (struct scsi_arq_status) : 1);
7791 	} else {
7792 		stat_size = 1;
7793 	}
7794 
7795 	ASSERT(mutex_owned(ST_MUTEX));
7796 
7797 	cdb = ucmd->uscsi_cdb;
7798 	cdblen = ucmd->uscsi_cdblen;
7799 
7800 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7801 	    "st_make_uscsi_cmd: buflen=%ld bcount=%ld\n",
7802 	    ucmd->uscsi_buflen, bp->b_bcount);
7803 	pkt = scsi_init_pkt(ROUTE, NULL,
7804 	    (bp->b_bcount > 0) ? bp : NULL,
7805 	    cdblen, stat_size, 0, 0, func, (caddr_t)un);
7806 	if (pkt == NULL) {
7807 		goto exit;
7808 	}
7809 
7810 	bcopy(cdb, pkt->pkt_cdbp, (uint_t)cdblen);
7811 
7812 #ifdef STDEBUG
7813 	if ((st_debug & 0xf) >= 6) {
7814 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
7815 		    "pkt_cdbp", (char *)cdb, cdblen);
7816 	}
7817 #endif
7818 
7819 	if (ucmd->uscsi_flags & USCSI_SILENT) {
7820 		pkt->pkt_flags |= FLAG_SILENT;
7821 	}
7822 
7823 	pkt->pkt_time = ucmd->uscsi_timeout;
7824 	pkt->pkt_comp = st_intr;
7825 	pkt->pkt_private = (opaque_t)bp;
7826 
7827 	SET_BP_PKT(bp, pkt);
7828 exit:
7829 	ASSERT(mutex_owned(ST_MUTEX));
7830 }
7831 
7832 
7833 /*
7834  * restart cmd currently at the head of the runq
7835  *
7836  * If scsi_transport() succeeds or the retries
7837  * count exhausted, restore the throttle that was
7838  * zeroed out in st_handle_intr_busy().
7839  *
7840  */
7841 static void
7842 st_intr_restart(void *arg)
7843 {
7844 	struct scsi_tape *un = arg;
7845 	struct buf *bp;
7846 	int status = TRAN_ACCEPT;
7847 
7848 	mutex_enter(ST_MUTEX);
7849 
7850 	ST_FUNC(ST_DEVINFO, st_intr_restart);
7851 
7852 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7853 	    "st_intr_restart(), un = 0x%p\n", (void *)un);
7854 
7855 	un->un_hib_tid = 0;
7856 
7857 	/*
7858 	 * move from waitq to runq, if there is anything on the waitq
7859 	 */
7860 	if ((bp = un->un_quef) == NULL) {
7861 		mutex_exit(ST_MUTEX);
7862 		return;
7863 	}
7864 
7865 	/*
7866 	 * Here we know :
7867 	 *	throttle = 0, via st_handle_intr_busy
7868 	 */
7869 
7870 	if (un->un_quel == bp) {
7871 		un->un_quel = NULL;
7872 		un->un_quef = NULL;	/* we know it's the first one */
7873 	} else {
7874 		un->un_quef = bp->b_actf;
7875 	}
7876 	bp->b_actf = NULL;
7877 
7878 	if (un->un_runqf) {
7879 		/*
7880 		 * not good, we don't want to requeue something after
7881 		 * another.
7882 		 */
7883 		mutex_exit(ST_MUTEX);
7884 		goto done_error;
7885 	} else {
7886 		un->un_runqf = bp;
7887 		un->un_runql = bp;
7888 	}
7889 
7890 	ST_DO_KSTATS(bp, kstat_waitq_to_runq);
7891 
7892 	mutex_exit(ST_MUTEX);
7893 
7894 	status = scsi_transport(BP_PKT(bp));
7895 
7896 	mutex_enter(ST_MUTEX);
7897 
7898 	if (status != TRAN_ACCEPT) {
7899 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
7900 		mutex_exit(ST_MUTEX);
7901 
7902 		if (status == TRAN_BUSY) {
7903 			if (st_handle_intr_busy(un, bp,
7904 			    ST_TRAN_BUSY_TIMEOUT) == 0)
7905 				return;	/* timeout is setup again */
7906 		}
7907 
7908 	} else {
7909 		un->un_tran_retry_ct = 0;
7910 		if (un->un_last_throttle) {
7911 			un->un_throttle = un->un_last_throttle;
7912 		}
7913 		mutex_exit(ST_MUTEX);
7914 		return;
7915 	}
7916 
7917 done_error:
7918 	ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
7919 	    "restart transport rejected\n");
7920 	bp->b_resid = bp->b_bcount;
7921 
7922 #ifndef __lock_lint
7923 	/*
7924 	 * warlock doesn't understand this potential
7925 	 * recursion?
7926 	 */
7927 	mutex_enter(ST_MUTEX);
7928 	if (un->un_last_throttle) {
7929 		un->un_throttle = un->un_last_throttle;
7930 	}
7931 	if (status != TRAN_ACCEPT)
7932 		ST_DO_ERRSTATS(un, st_transerrs);
7933 	ST_DO_KSTATS(bp, kstat_waitq_exit);
7934 	SET_PE_FLAG(un);
7935 	st_bioerror(bp, EIO);
7936 	st_done_and_mutex_exit(un, bp);
7937 #endif
7938 	ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
7939 	    "busy restart aborted\n");
7940 }
7941 
7942 /*
7943  * st_check_media():
7944  * Periodically check the media state using scsi_watch service;
7945  * this service calls back after TUR and possibly request sense
7946  * the callback handler (st_media_watch_cb()) decodes the request sense
7947  * data (if any)
7948  */
7949 
7950 static int
7951 st_check_media(dev_t dev, enum mtio_state state)
7952 {
7953 	int rval = 0;
7954 	enum mtio_state	prev_state;
7955 	opaque_t token = NULL;
7956 
7957 	GET_SOFT_STATE(dev);
7958 
7959 	ST_FUNC(ST_DEVINFO, st_check_media);
7960 
7961 	mutex_enter(ST_MUTEX);
7962 
7963 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
7964 	    "st_check_media:state=%x, mediastate=%x\n",
7965 	    state, un->un_mediastate);
7966 
7967 	prev_state = un->un_mediastate;
7968 
7969 	/*
7970 	 * is there anything to do?
7971 	 */
7972 retry:
7973 	if (state == un->un_mediastate || un->un_mediastate == MTIO_NONE) {
7974 		/*
7975 		 * submit the request to the scsi_watch service;
7976 		 * scsi_media_watch_cb() does the real work
7977 		 */
7978 		mutex_exit(ST_MUTEX);
7979 		token = scsi_watch_request_submit(ST_SCSI_DEVP,
7980 		    st_check_media_time, SENSE_LENGTH,
7981 		    st_media_watch_cb, (caddr_t)dev);
7982 		if (token == NULL) {
7983 			rval = EAGAIN;
7984 			goto done;
7985 		}
7986 		mutex_enter(ST_MUTEX);
7987 
7988 		un->un_swr_token = token;
7989 		un->un_specified_mediastate = state;
7990 
7991 		/*
7992 		 * now wait for media change
7993 		 * we will not be signalled unless mediastate == state but it
7994 		 * still better to test for this condition, since there
7995 		 * is a 5 sec cv_broadcast delay when
7996 		 *  mediastate == MTIO_INSERTED
7997 		 */
7998 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
7999 		    "st_check_media:waiting for media state change\n");
8000 		while (un->un_mediastate == state) {
8001 			if (cv_wait_sig(&un->un_state_cv, ST_MUTEX) == 0) {
8002 				mutex_exit(ST_MUTEX);
8003 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8004 				    "st_check_media:waiting for media state "
8005 				    "was interrupted\n");
8006 				rval = EINTR;
8007 				goto done;
8008 			}
8009 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8010 			    "st_check_media:received signal, state=%x\n",
8011 			    un->un_mediastate);
8012 		}
8013 	}
8014 
8015 	/*
8016 	 * if we transitioned to MTIO_INSERTED, media has really been
8017 	 * inserted.  If TUR fails, it is probably a exabyte slow spin up.
8018 	 * Reset and retry the state change.  If everything is ok, replay
8019 	 * the open() logic.
8020 	 */
8021 	if ((un->un_mediastate == MTIO_INSERTED) &&
8022 	    (un->un_state == ST_STATE_OFFLINE)) {
8023 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8024 		    "st_check_media: calling st_cmd to confirm inserted\n");
8025 
8026 		/*
8027 		 * set this early so that TUR will make it through strategy
8028 		 * without triggering a st_tape_init().  We needed it set
8029 		 * before calling st_tape_init() ourselves anyway.  If TUR
8030 		 * fails, set it back
8031 		 */
8032 		un->un_state = ST_STATE_INITIALIZING;
8033 
8034 		/*
8035 		 * If not reserved fail as getting reservation conflict
8036 		 * will make this hang forever.
8037 		 */
8038 		if ((un->un_rsvd_status &
8039 		    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
8040 			mutex_exit(ST_MUTEX);
8041 			rval = EACCES;
8042 			goto done;
8043 		}
8044 		rval = st_cmd(dev, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
8045 		if (rval == EACCES) {
8046 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8047 			    "st_check_media: TUR got Reservation Conflict\n");
8048 			mutex_exit(ST_MUTEX);
8049 			goto done;
8050 		}
8051 		if (rval) {
8052 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8053 			    "st_check_media: TUR failed, going to retry\n");
8054 			un->un_mediastate = prev_state;
8055 			un->un_state = ST_STATE_OFFLINE;
8056 			goto retry;
8057 		}
8058 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8059 		    "st_check_media: media inserted\n");
8060 
8061 		/* this also rewinds the tape */
8062 		rval = st_tape_init(dev);
8063 		if (rval != 0) {
8064 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8065 			    "st_check_media : OFFLINE init failure ");
8066 			un->un_state = ST_STATE_OFFLINE;
8067 			un->un_pos.pmode = invalid;
8068 		} else {
8069 			un->un_state = ST_STATE_OPEN_PENDING_IO;
8070 			un->un_pos.fileno = 0;
8071 			un->un_pos.blkno = 0;
8072 			un->un_pos.lgclblkno = 0;
8073 		}
8074 	} else if ((un->un_mediastate == MTIO_EJECTED) &&
8075 	    (un->un_state != ST_STATE_OFFLINE)) {
8076 		/*
8077 		 * supported devices must be rewound before ejection
8078 		 * rewind resets fileno & blkno
8079 		 */
8080 		un->un_laststate = un->un_state;
8081 		un->un_state = ST_STATE_OFFLINE;
8082 	}
8083 	mutex_exit(ST_MUTEX);
8084 done:
8085 	if (token) {
8086 		(void) scsi_watch_request_terminate(token,
8087 		    SCSI_WATCH_TERMINATE_WAIT);
8088 		mutex_enter(ST_MUTEX);
8089 		un->un_swr_token = (opaque_t)NULL;
8090 		mutex_exit(ST_MUTEX);
8091 	}
8092 
8093 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG, "st_check_media: done\n");
8094 
8095 	return (rval);
8096 }
8097 
8098 /*
8099  * st_media_watch_cb() is called by scsi_watch_thread for
8100  * verifying the request sense data (if any)
8101  */
8102 static int
8103 st_media_watch_cb(caddr_t arg, struct scsi_watch_result *resultp)
8104 {
8105 	struct scsi_status *statusp = resultp->statusp;
8106 	struct scsi_extended_sense *sensep = resultp->sensep;
8107 	uchar_t actual_sense_length = resultp->actual_sense_length;
8108 	struct scsi_tape *un;
8109 	enum mtio_state state = MTIO_NONE;
8110 	int instance;
8111 	dev_t dev = (dev_t)arg;
8112 
8113 	instance = MTUNIT(dev);
8114 	if ((un = ddi_get_soft_state(st_state, instance)) == NULL) {
8115 		return (-1);
8116 	}
8117 
8118 	mutex_enter(ST_MUTEX);
8119 	ST_FUNC(ST_DEVINFO, st_media_watch_cb);
8120 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8121 	    "st_media_watch_cb: status=%x, sensep=%p, len=%x\n",
8122 	    *((char *)statusp), (void *)sensep,
8123 	    actual_sense_length);
8124 
8125 
8126 	/*
8127 	 * if there was a check condition then sensep points to valid
8128 	 * sense data
8129 	 * if status was not a check condition but a reservation or busy
8130 	 * status then the new state is MTIO_NONE
8131 	 */
8132 	if (sensep) {
8133 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8134 		    "st_media_watch_cb: KEY=%x, ASC=%x, ASCQ=%x\n",
8135 		    sensep->es_key, sensep->es_add_code, sensep->es_qual_code);
8136 
8137 		switch (un->un_dp->type) {
8138 		default:
8139 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8140 			    "st_media_watch_cb: unknown drive type %d, "
8141 			    "default to ST_TYPE_HP\n", un->un_dp->type);
8142 		/* FALLTHROUGH */
8143 
8144 		case ST_TYPE_STC3490:	/* STK 4220 1/2" cartridge */
8145 		case ST_TYPE_FUJI:	/* 1/2" cartridge */
8146 		case ST_TYPE_HP:	/* HP 88780 1/2" reel */
8147 			if (un->un_dp->type == ST_TYPE_FUJI) {
8148 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8149 				    "st_media_watch_cb: ST_TYPE_FUJI\n");
8150 			} else {
8151 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8152 				    "st_media_watch_cb: ST_TYPE_HP\n");
8153 			}
8154 			switch (sensep->es_key) {
8155 			case KEY_UNIT_ATTENTION:
8156 				/* not ready to ready transition */
8157 				/* hp/es_qual_code == 80 on>off>on */
8158 				/* hp/es_qual_code == 0 on>off>unld>ld>on */
8159 				if (sensep->es_add_code == 0x28) {
8160 					state = MTIO_INSERTED;
8161 				}
8162 				break;
8163 			case KEY_NOT_READY:
8164 				/* in process, rewinding or loading */
8165 				if ((sensep->es_add_code == 0x04) &&
8166 				    (sensep->es_qual_code == 0x00)) {
8167 					state = MTIO_EJECTED;
8168 				}
8169 				break;
8170 			}
8171 			break;
8172 
8173 		case ST_TYPE_EXB8500:	/* Exabyte 8500 */
8174 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8175 			    "st_media_watch_cb: ST_TYPE_EXB8500\n");
8176 			switch (sensep->es_key) {
8177 			case KEY_UNIT_ATTENTION:
8178 				/* operator medium removal request */
8179 				if ((sensep->es_add_code == 0x5a) &&
8180 				    (sensep->es_qual_code == 0x01)) {
8181 					state = MTIO_EJECTED;
8182 				/* not ready to ready transition */
8183 				} else if ((sensep->es_add_code == 0x28) &&
8184 				    (sensep->es_qual_code == 0x00)) {
8185 					state = MTIO_INSERTED;
8186 				}
8187 				break;
8188 			case KEY_NOT_READY:
8189 				/* medium not present */
8190 				if (sensep->es_add_code == 0x3a) {
8191 					state = MTIO_EJECTED;
8192 				}
8193 				break;
8194 			}
8195 			break;
8196 		case ST_TYPE_EXABYTE:	/* Exabyte 8200 */
8197 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8198 			    "st_media_watch_cb: ST_TYPE_EXABYTE\n");
8199 			switch (sensep->es_key) {
8200 			case KEY_NOT_READY:
8201 				if ((sensep->es_add_code == 0x04) &&
8202 				    (sensep->es_qual_code == 0x00)) {
8203 					/* volume not mounted? */
8204 					state = MTIO_EJECTED;
8205 				} else if (sensep->es_add_code == 0x3a) {
8206 					state = MTIO_EJECTED;
8207 				}
8208 				break;
8209 			case KEY_UNIT_ATTENTION:
8210 				state = MTIO_EJECTED;
8211 				break;
8212 			}
8213 			break;
8214 
8215 		case ST_TYPE_DLT:		/* quantum DLT4xxx */
8216 			switch (sensep->es_key) {
8217 			case KEY_UNIT_ATTENTION:
8218 				if (sensep->es_add_code == 0x28) {
8219 					state = MTIO_INSERTED;
8220 				}
8221 				break;
8222 			case KEY_NOT_READY:
8223 				if (sensep->es_add_code == 0x04) {
8224 					/* in transition but could be either */
8225 					state = un->un_specified_mediastate;
8226 				} else if ((sensep->es_add_code == 0x3a) &&
8227 				    (sensep->es_qual_code == 0x00)) {
8228 					state = MTIO_EJECTED;
8229 				}
8230 				break;
8231 			}
8232 			break;
8233 		}
8234 	} else if (*((char *)statusp) == STATUS_GOOD) {
8235 		state = MTIO_INSERTED;
8236 	}
8237 
8238 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8239 	    "st_media_watch_cb:state=%x, specified=%x\n",
8240 	    state, un->un_specified_mediastate);
8241 
8242 	/*
8243 	 * now signal the waiting thread if this is *not* the specified state;
8244 	 * delay the signal if the state is MTIO_INSERTED
8245 	 * to allow the target to recover
8246 	 */
8247 	if (state != un->un_specified_mediastate) {
8248 		un->un_mediastate = state;
8249 		if (state == MTIO_INSERTED) {
8250 			/*
8251 			 * delay the signal to give the drive a chance
8252 			 * to do what it apparently needs to do
8253 			 */
8254 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8255 			    "st_media_watch_cb:delayed cv_broadcast\n");
8256 			un->un_delay_tid = timeout(st_delayed_cv_broadcast,
8257 			    un, drv_usectohz((clock_t)MEDIA_ACCESS_DELAY));
8258 		} else {
8259 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8260 			    "st_media_watch_cb:immediate cv_broadcast\n");
8261 			cv_broadcast(&un->un_state_cv);
8262 		}
8263 	}
8264 	mutex_exit(ST_MUTEX);
8265 	return (0);
8266 }
8267 
8268 /*
8269  * delayed cv_broadcast to allow for target to recover
8270  * from media insertion
8271  */
8272 static void
8273 st_delayed_cv_broadcast(void *arg)
8274 {
8275 	struct scsi_tape *un = arg;
8276 
8277 	ST_FUNC(ST_DEVINFO, st_delayed_cv_broadcast);
8278 
8279 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8280 	    "st_delayed_cv_broadcast:delayed cv_broadcast\n");
8281 
8282 	mutex_enter(ST_MUTEX);
8283 	cv_broadcast(&un->un_state_cv);
8284 	mutex_exit(ST_MUTEX);
8285 }
8286 
8287 /*
8288  * restart cmd currently at the start of the waitq
8289  */
8290 static void
8291 st_start_restart(void *arg)
8292 {
8293 	struct scsi_tape *un = arg;
8294 
8295 	ST_FUNC(ST_DEVINFO, st_start_restart);
8296 
8297 	ASSERT(un != NULL);
8298 
8299 	mutex_enter(ST_MUTEX);
8300 
8301 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8302 	    "st_tran_restart()\n");
8303 
8304 	if (un->un_quef) {
8305 		st_start(un);
8306 	}
8307 
8308 	mutex_exit(ST_MUTEX);
8309 }
8310 
8311 
8312 /*
8313  * Command completion processing
8314  *
8315  */
8316 static void
8317 st_intr(struct scsi_pkt *pkt)
8318 {
8319 	struct scsi_tape *un;
8320 	struct buf *last_runqf;
8321 	struct buf *bp;
8322 	int action = COMMAND_DONE;
8323 	clock_t	timout;
8324 	int	status;
8325 
8326 
8327 	bp = pkt->pkt_private;
8328 
8329 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
8330 
8331 	ST_FUNC(ST_DEVINFO, st_intr);
8332 
8333 	mutex_enter(ST_MUTEX);
8334 
8335 	un->un_rqs_state &= ~(ST_RQS_ERROR);
8336 
8337 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_intr()\n");
8338 
8339 	if (pkt->pkt_reason != CMD_CMPLT) {
8340 
8341 		/* If device has gone away not much else to do */
8342 		if (pkt->pkt_reason == CMD_DEV_GONE) {
8343 			action = COMMAND_DONE_ERROR;
8344 		} else if (un->un_state == ST_STATE_SENSING) {
8345 			ST_DO_ERRSTATS(un, st_transerrs);
8346 			action = COMMAND_DONE_ERROR;
8347 		} else {
8348 			action = st_handle_incomplete(un, bp);
8349 		}
8350 	/*
8351 	 * At this point we know that the command was successfully
8352 	 * completed. Now what?
8353 	 */
8354 	} else if (un->un_arq_enabled &&
8355 	    (pkt->pkt_state & STATE_ARQ_DONE)) {
8356 		/*
8357 		 * the transport layer successfully completed an autorqsense
8358 		 */
8359 		action = st_handle_autosense(un, bp);
8360 
8361 	} else if (un->un_state == ST_STATE_SENSING) {
8362 		/*
8363 		 * okay. We were running a REQUEST SENSE. Find
8364 		 * out what to do next.
8365 		 * some actions are based on un_state, hence
8366 		 * restore the state st was in before ST_STATE_SENSING.
8367 		 */
8368 		un->un_state = un->un_laststate;
8369 		action = st_handle_sense(un, bp);
8370 		/*
8371 		 * set pkt back to original packet in case we will have
8372 		 * to requeue it
8373 		 */
8374 		pkt = BP_PKT(bp);
8375 	} else  if ((SCBP(pkt)->sts_busy) || (SCBP(pkt)->sts_chk)) {
8376 		/*
8377 		 * Okay, we weren't running a REQUEST SENSE. Call a routine
8378 		 * to see if the status bits we're okay. If a request sense
8379 		 * is to be run, that will happen.
8380 		 */
8381 		action = st_check_error(un, pkt);
8382 	}
8383 
8384 	if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
8385 		switch (action) {
8386 			case QUE_COMMAND:
8387 				/*
8388 				 * return cmd to head to the queue
8389 				 * since we are suspending so that
8390 				 * it gets restarted during resume
8391 				 */
8392 				if (un->un_runqf) {
8393 					last_runqf = un->un_runqf;
8394 					un->un_runqf = bp;
8395 					bp->b_actf = last_runqf;
8396 				} else {
8397 					bp->b_actf = NULL;
8398 					un->un_runqf = bp;
8399 					un->un_runql = bp;
8400 				}
8401 				action = JUST_RETURN;
8402 				break;
8403 
8404 			case QUE_SENSE:
8405 				action = COMMAND_DONE_ERROR;
8406 				break;
8407 
8408 			default:
8409 				break;
8410 		}
8411 	}
8412 
8413 	/*
8414 	 * Restore old state if we were sensing.
8415 	 */
8416 	if (un->un_state == ST_STATE_SENSING && action != QUE_SENSE) {
8417 		un->un_state = un->un_laststate;
8418 	}
8419 
8420 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8421 	    "st_intr: pkt=%p, bp=%p, action=%x, status=%x\n",
8422 	    (void *)pkt, (void *)bp, action, SCBP_C(pkt));
8423 
8424 
8425 	switch (action) {
8426 	case COMMAND_DONE_EACCES:
8427 		/* this is to report a reservation conflict */
8428 		st_bioerror(bp, EACCES);
8429 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8430 		    "Reservation Conflict \n");
8431 		un->un_pos.pmode = invalid;
8432 
8433 		/*FALLTHROUGH*/
8434 	case COMMAND_DONE_ERROR:
8435 		if (un->un_pos.eof < ST_EOT_PENDING &&
8436 		    un->un_state >= ST_STATE_OPEN) {
8437 			/*
8438 			 * all errors set state of the tape to 'unknown'
8439 			 * unless we're at EOT or are doing append testing.
8440 			 * If sense key was illegal request, preserve state.
8441 			 */
8442 			if (un->un_status != KEY_ILLEGAL_REQUEST) {
8443 				un->un_pos.pmode = invalid;
8444 			}
8445 		}
8446 
8447 		un->un_err_resid = bp->b_resid = bp->b_bcount;
8448 		/*
8449 		 * since we have an error (COMMAND_DONE_ERROR), we want to
8450 		 * make sure an error ocurrs, so make sure at least EIO is
8451 		 * returned
8452 		 */
8453 		if (geterror(bp) == 0)
8454 			st_bioerror(bp, EIO);
8455 
8456 		SET_PE_FLAG(un);
8457 		if (!(un->un_rqs_state & ST_RQS_ERROR) &&
8458 		    (un->un_errno == EIO)) {
8459 			un->un_rqs_state &= ~(ST_RQS_VALID);
8460 		}
8461 		goto done;
8462 
8463 	case COMMAND_DONE_ERROR_RECOVERED:
8464 		un->un_err_resid = bp->b_resid = bp->b_bcount;
8465 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
8466 		    "st_intr(): COMMAND_DONE_ERROR_RECOVERED");
8467 		if (geterror(bp) == 0) {
8468 			st_bioerror(bp, EIO);
8469 		}
8470 		SET_PE_FLAG(un);
8471 		if (!(un->un_rqs_state & ST_RQS_ERROR) &&
8472 		    (un->un_errno == EIO)) {
8473 			un->un_rqs_state &= ~(ST_RQS_VALID);
8474 		}
8475 		/*FALLTHROUGH*/
8476 	case COMMAND_DONE:
8477 		st_set_state(un);
8478 done:
8479 		ST_DO_KSTATS(bp, kstat_runq_exit);
8480 		st_done_and_mutex_exit(un, bp);
8481 		return;
8482 
8483 	case QUE_SENSE:
8484 		if ((un->un_ncmds > 1) && !un->un_flush_on_errors)
8485 			goto sense_error;
8486 
8487 		if (un->un_state != ST_STATE_SENSING) {
8488 			un->un_laststate = un->un_state;
8489 			un->un_state = ST_STATE_SENSING;
8490 		}
8491 
8492 		un->un_rqs->pkt_private = (opaque_t)bp;
8493 		bzero(ST_RQSENSE, SENSE_LENGTH);
8494 
8495 		if (un->un_throttle) {
8496 			un->un_last_throttle = un->un_throttle;
8497 			un->un_throttle = 0;
8498 		}
8499 
8500 		mutex_exit(ST_MUTEX);
8501 
8502 		/*
8503 		 * never retry this, some other command will have nuked the
8504 		 * sense, anyway
8505 		 */
8506 		status = scsi_transport(un->un_rqs);
8507 
8508 		mutex_enter(ST_MUTEX);
8509 
8510 		if (un->un_last_throttle) {
8511 			un->un_throttle = un->un_last_throttle;
8512 		}
8513 
8514 		if (status == TRAN_ACCEPT) {
8515 			mutex_exit(ST_MUTEX);
8516 			return;
8517 		}
8518 		if (status != TRAN_BUSY)
8519 			ST_DO_ERRSTATS(un, st_transerrs);
8520 sense_error:
8521 		un->un_pos.pmode = invalid;
8522 		st_bioerror(bp, EIO);
8523 		SET_PE_FLAG(un);
8524 		goto done;
8525 
8526 	case QUE_BUSY_COMMAND:
8527 		/* longish timeout */
8528 		timout = ST_STATUS_BUSY_TIMEOUT;
8529 		goto que_it_up;
8530 
8531 	case QUE_COMMAND:
8532 		/* short timeout */
8533 		timout = ST_TRAN_BUSY_TIMEOUT;
8534 que_it_up:
8535 		/*
8536 		 * let st_handle_intr_busy put this bp back on waitq and make
8537 		 * checks to see if it is ok to requeue the command.
8538 		 */
8539 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
8540 
8541 		/*
8542 		 * Save the throttle before setting up the timeout
8543 		 */
8544 		if (un->un_throttle) {
8545 			un->un_last_throttle = un->un_throttle;
8546 		}
8547 		mutex_exit(ST_MUTEX);
8548 		if (st_handle_intr_busy(un, bp, timout) == 0)
8549 			return;		/* timeout is setup again */
8550 
8551 		mutex_enter(ST_MUTEX);
8552 		un->un_pos.pmode = invalid;
8553 		un->un_err_resid = bp->b_resid = bp->b_bcount;
8554 		st_bioerror(bp, EIO);
8555 		SET_PE_FLAG(un);
8556 		goto done;
8557 
8558 	case QUE_LAST_COMMAND:
8559 
8560 		if ((un->un_ncmds > 1) && !un->un_flush_on_errors) {
8561 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
8562 			    "un_ncmds: %d can't retry cmd \n", un->un_ncmds);
8563 			goto last_command_error;
8564 		}
8565 		mutex_exit(ST_MUTEX);
8566 		if (st_handle_intr_retry_lcmd(un, bp) == 0)
8567 			return;
8568 		mutex_enter(ST_MUTEX);
8569 last_command_error:
8570 		un->un_err_resid = bp->b_resid = bp->b_bcount;
8571 		un->un_pos.pmode = invalid;
8572 		st_bioerror(bp, EIO);
8573 		SET_PE_FLAG(un);
8574 		goto done;
8575 
8576 	case JUST_RETURN:
8577 	default:
8578 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
8579 		mutex_exit(ST_MUTEX);
8580 		return;
8581 	}
8582 	/*NOTREACHED*/
8583 }
8584 
8585 static int
8586 st_handle_incomplete(struct scsi_tape *un, struct buf *bp)
8587 {
8588 	static char *fail = "SCSI transport failed: reason '%s': %s\n";
8589 	int rval = COMMAND_DONE_ERROR;
8590 	struct scsi_pkt *pkt = (un->un_state == ST_STATE_SENSING) ?
8591 	    un->un_rqs : BP_PKT(bp);
8592 	int result;
8593 
8594 	ST_FUNC(ST_DEVINFO, st_handle_incomplete);
8595 
8596 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8597 	    "st_handle_incomplete(): dev = 0x%lx\n", un->un_dev);
8598 
8599 	ASSERT(mutex_owned(ST_MUTEX));
8600 
8601 	switch (pkt->pkt_reason) {
8602 	case CMD_INCOMPLETE:	/* tran stopped with not normal state */
8603 		/*
8604 		 * this occurs when accessing a powered down drive, no
8605 		 * need to complain; just fail the open
8606 		 */
8607 		ST_CDB(ST_DEVINFO, "Incomplete CDB", (char *)pkt->pkt_cdbp);
8608 
8609 		/*
8610 		 * if we have commands outstanding in HBA, and a command
8611 		 * comes back incomplete, we're hosed, so reset target
8612 		 * If we have the bus, but cmd_incomplete, we probably just
8613 		 * have a failed selection, so don't reset the target, just
8614 		 * requeue the command and try again
8615 		 */
8616 		if ((un->un_ncmds > 1) || (pkt->pkt_state != STATE_GOT_BUS)) {
8617 			goto reset_target;
8618 		}
8619 
8620 		/*
8621 		 * Retry selection a couple more times if we're
8622 		 * open.  If opening, we only try just once to
8623 		 * reduce probe time for nonexistant devices.
8624 		 */
8625 		if ((un->un_laststate > ST_STATE_OPENING) &&
8626 		    ((int)un->un_retry_ct < st_selection_retry_count)) {
8627 			rval = QUE_COMMAND;
8628 		}
8629 		ST_DO_ERRSTATS(un, st_transerrs);
8630 		break;
8631 
8632 	case CMD_ABORTED:
8633 		/*
8634 		 * most likely this is caused by flush-on-error support. If
8635 		 * it was not there, the we're in trouble.
8636 		 */
8637 		if (!un->un_flush_on_errors) {
8638 			un->un_status = SUN_KEY_FATAL;
8639 			goto reset_target;
8640 		}
8641 
8642 		st_set_pe_errno(un);
8643 		bioerror(bp, un->un_errno);
8644 		if (un->un_errno)
8645 			return (COMMAND_DONE_ERROR);
8646 		else
8647 			return (COMMAND_DONE);
8648 
8649 	case CMD_TIMEOUT:	/* Command timed out */
8650 		un->un_status = SUN_KEY_TIMEOUT;
8651 
8652 		/*FALLTHROUGH*/
8653 	default:
8654 reset_target:
8655 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
8656 		    "transport completed with %s\n",
8657 		    scsi_rname(pkt->pkt_reason));
8658 		ST_DO_ERRSTATS(un, st_transerrs);
8659 		if ((pkt->pkt_state & STATE_GOT_TARGET) &&
8660 		    ((pkt->pkt_statistics & (STAT_BUS_RESET | STAT_DEV_RESET |
8661 		    STAT_ABORTED)) == 0)) {
8662 
8663 			/*
8664 			 * If we haven't reserved the drive don't reset it.
8665 			 */
8666 			if ((un->un_rsvd_status &
8667 			    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
8668 				return (rval);
8669 			}
8670 
8671 			/*
8672 			 * if we aren't lost yet we will be soon.
8673 			 */
8674 			un->un_pos.pmode = invalid;
8675 
8676 			mutex_exit(ST_MUTEX);
8677 
8678 			result = scsi_reset(ROUTE, RESET_TARGET);
8679 			/*
8680 			 * if target reset fails, then pull the chain
8681 			 */
8682 			if (result == 0) {
8683 				result = scsi_reset(ROUTE, RESET_ALL);
8684 			}
8685 			mutex_enter(ST_MUTEX);
8686 
8687 			if ((result == 0) && (un->un_state >= ST_STATE_OPEN)) {
8688 				/* no hope left to recover */
8689 				scsi_log(ST_DEVINFO, st_label, CE_WARN,
8690 				    "recovery by resets failed\n");
8691 				return (rval);
8692 			}
8693 		}
8694 	}
8695 
8696 	if ((pkt->pkt_reason == CMD_RESET) || (pkt->pkt_statistics &
8697 	    (STAT_BUS_RESET | STAT_DEV_RESET))) {
8698 		if ((un->un_rsvd_status & ST_RESERVE)) {
8699 			un->un_rsvd_status |= ST_LOST_RESERVE;
8700 			ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
8701 			    "Lost Reservation\n");
8702 		}
8703 	}
8704 
8705 	if ((int)un->un_retry_ct++ < st_retry_count) {
8706 		if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
8707 			rval = QUE_COMMAND;
8708 		} else if (bp == un->un_sbufp) {
8709 			switch ((uchar_t)(uintptr_t)bp->b_forw) {
8710 			case SCMD_MODE_SENSE:
8711 			case SCMD_MODE_SELECT:
8712 			case SCMD_READ_BLKLIM:
8713 			case SCMD_REWIND:
8714 			case SCMD_LOAD:
8715 			case SCMD_TEST_UNIT_READY:
8716 				/*
8717 				 * These commands can be rerun with impunity
8718 				 */
8719 				rval = QUE_COMMAND;
8720 				break;
8721 
8722 			default:
8723 				break;
8724 			}
8725 		}
8726 	} else {
8727 		rval = COMMAND_DONE_ERROR;
8728 	}
8729 
8730 	if (un->un_state >= ST_STATE_OPEN) {
8731 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
8732 		    fail, scsi_rname(pkt->pkt_reason),
8733 		    (rval == COMMAND_DONE_ERROR)?
8734 		    "giving up" : "retrying command");
8735 	}
8736 	return (rval);
8737 }
8738 
8739 /*
8740  * if the device is busy, then put this bp back on the waitq, on the
8741  * interrupt thread, where we want the head of the queue and not the
8742  * end
8743  *
8744  * The callers of this routine should take measures to save the
8745  * un_throttle in un_last_throttle which will be restored in
8746  * st_intr_restart(). The only exception should be st_intr_restart()
8747  * calling this routine for which the saving is already done.
8748  */
8749 static int
8750 st_handle_intr_busy(struct scsi_tape *un, struct buf *bp,
8751 	clock_t timeout_interval)
8752 {
8753 	struct buf *last_quef;
8754 	int rval = 0;
8755 
8756 	mutex_enter(ST_MUTEX);
8757 
8758 	ST_FUNC(ST_DEVINFO, st_handle_intr_busy);
8759 
8760 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8761 	    "st_handle_intr_busy(), un = 0x%p\n", (void *)un);
8762 
8763 	/*
8764 	 * Check to see if we hit the retry timeout. We check to make sure
8765 	 * this is the first one on the runq and make sure we have not
8766 	 * queued up any more, so this one has to be the last on the list
8767 	 * also. If it is not, we have to fail.  If it is not the first, but
8768 	 * is the last we are in trouble anyway, as we are in the interrupt
8769 	 * context here.
8770 	 */
8771 	if (((int)un->un_tran_retry_ct++ > st_retry_count) ||
8772 	    ((un->un_runqf != bp) && (un->un_runql != bp))) {
8773 		rval = -1;
8774 		goto exit;
8775 	}
8776 
8777 	/* put the bp back on the waitq */
8778 	if (un->un_quef) {
8779 		last_quef = un->un_quef;
8780 		un->un_quef = bp;
8781 		bp->b_actf = last_quef;
8782 	} else  {
8783 		bp->b_actf = NULL;
8784 		un->un_quef = bp;
8785 		un->un_quel = bp;
8786 	}
8787 
8788 	/*
8789 	 * We know that this is the first and last on the runq at this time,
8790 	 * so we just nullify those two queues
8791 	 */
8792 	un->un_runqf = NULL;
8793 	un->un_runql = NULL;
8794 
8795 	/*
8796 	 * We don't want any other commands being started in the mean time.
8797 	 * If start had just released mutex after putting something on the
8798 	 * runq, we won't even get here.
8799 	 */
8800 	un->un_throttle = 0;
8801 
8802 	/*
8803 	 * send a marker pkt, if appropriate
8804 	 */
8805 	st_hba_unflush(un);
8806 
8807 	/*
8808 	 * all queues are aligned, we are just waiting to
8809 	 * transport
8810 	 */
8811 	un->un_hib_tid = timeout(st_intr_restart, un, timeout_interval);
8812 
8813 exit:
8814 	mutex_exit(ST_MUTEX);
8815 	return (rval);
8816 }
8817 
8818 static int
8819 st_handle_sense(struct scsi_tape *un, struct buf *bp)
8820 {
8821 	struct scsi_pkt *rqpkt = un->un_rqs;
8822 	int rval = COMMAND_DONE_ERROR;
8823 	int amt;
8824 
8825 	ST_FUNC(ST_DEVINFO, st_handle_sense);
8826 
8827 	ASSERT(mutex_owned(ST_MUTEX));
8828 
8829 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8830 	    "st_handle_sense()\n");
8831 
8832 	if (SCBP(rqpkt)->sts_busy) {
8833 		ST_DEBUG4(ST_DEVINFO, st_label, CE_WARN,
8834 		    "busy unit on request sense\n");
8835 		if ((int)un->un_retry_ct++ < st_retry_count) {
8836 			rval = QUE_BUSY_COMMAND;
8837 		}
8838 		return (rval);
8839 	} else if (SCBP(rqpkt)->sts_chk) {
8840 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
8841 		    "Check Condition on REQUEST SENSE\n");
8842 		return (rval);
8843 	}
8844 
8845 	/* was there enough data? */
8846 	amt = (int)SENSE_LENGTH - rqpkt->pkt_resid;
8847 	if ((rqpkt->pkt_state & STATE_XFERRED_DATA) == 0 ||
8848 	    (amt < SUN_MIN_SENSE_LENGTH)) {
8849 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
8850 		    "REQUEST SENSE couldn't get sense data\n");
8851 		return (rval);
8852 	}
8853 	return (st_decode_sense(un, bp, amt, SCBP(rqpkt)));
8854 }
8855 
8856 static int
8857 st_handle_autosense(struct scsi_tape *un, struct buf *bp)
8858 {
8859 	struct scsi_pkt *pkt = BP_PKT(bp);
8860 	struct scsi_arq_status *arqstat =
8861 	    (struct scsi_arq_status *)pkt->pkt_scbp;
8862 	int rval = COMMAND_DONE_ERROR;
8863 	int amt;
8864 
8865 	ST_FUNC(ST_DEVINFO, st_handle_autosense);
8866 
8867 	ASSERT(mutex_owned(ST_MUTEX));
8868 
8869 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8870 	    "st_handle_autosense()\n");
8871 
8872 	if (arqstat->sts_rqpkt_status.sts_busy) {
8873 		ST_DEBUG4(ST_DEVINFO, st_label, CE_WARN,
8874 		    "busy unit on request sense\n");
8875 		/*
8876 		 * we return QUE_SENSE so st_intr will setup the SENSE cmd.
8877 		 * the disadvantage is that we do not have any delay for the
8878 		 * second retry of rqsense and we have to keep a packet around
8879 		 */
8880 		return (QUE_SENSE);
8881 
8882 	} else if (arqstat->sts_rqpkt_reason != CMD_CMPLT) {
8883 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
8884 		    "transport error on REQUEST SENSE\n");
8885 		if ((arqstat->sts_rqpkt_state & STATE_GOT_TARGET) &&
8886 		    ((arqstat->sts_rqpkt_statistics &
8887 		    (STAT_BUS_RESET | STAT_DEV_RESET | STAT_ABORTED)) == 0)) {
8888 			mutex_exit(ST_MUTEX);
8889 			if (scsi_reset(ROUTE, RESET_TARGET) == 0) {
8890 				/*
8891 				 * if target reset fails, then pull the chain
8892 				 */
8893 				if (scsi_reset(ROUTE, RESET_ALL) == 0) {
8894 					ST_DEBUG6(ST_DEVINFO, st_label,
8895 					    CE_WARN,
8896 					    "recovery by resets failed\n");
8897 				}
8898 			}
8899 			mutex_enter(ST_MUTEX);
8900 		}
8901 		return (rval);
8902 
8903 	} else if (arqstat->sts_rqpkt_status.sts_chk) {
8904 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
8905 		    "Check Condition on REQUEST SENSE\n");
8906 		return (rval);
8907 	}
8908 
8909 
8910 	/* was there enough data? */
8911 	amt = (int)SENSE_LENGTH - arqstat->sts_rqpkt_resid;
8912 	if ((arqstat->sts_rqpkt_state & STATE_XFERRED_DATA) == 0 ||
8913 	    (amt < SUN_MIN_SENSE_LENGTH)) {
8914 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
8915 		    "REQUEST SENSE couldn't get sense data\n");
8916 		return (rval);
8917 	}
8918 
8919 	bcopy(&arqstat->sts_sensedata, ST_RQSENSE, SENSE_LENGTH);
8920 
8921 	return (st_decode_sense(un, bp, amt, &arqstat->sts_rqpkt_status));
8922 }
8923 
8924 static int
8925 st_decode_sense(struct scsi_tape *un, struct buf *bp,  int amt,
8926 	struct scsi_status *statusp)
8927 {
8928 	struct scsi_pkt *pkt = BP_PKT(bp);
8929 	int rval = COMMAND_DONE_ERROR;
8930 	long resid;
8931 	struct scsi_extended_sense *sensep = ST_RQSENSE;
8932 	int severity;
8933 	int get_error;
8934 
8935 	ST_FUNC(ST_DEVINFO, st_decode_sense);
8936 
8937 	ASSERT(mutex_owned(ST_MUTEX));
8938 
8939 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8940 	    "st_decode_sense()\n");
8941 
8942 	/*
8943 	 * For uscsi commands, squirrel away a copy of the
8944 	 * results of the Request Sense.
8945 	 */
8946 	if (USCSI_CMD(bp)) {
8947 		struct uscsi_cmd *ucmd = BP_UCMD(bp);
8948 		ucmd->uscsi_rqstatus = *(uchar_t *)statusp;
8949 		if (ucmd->uscsi_rqlen && un->un_srqbufp) {
8950 			uchar_t rqlen = min((uchar_t)amt, ucmd->uscsi_rqlen);
8951 			ucmd->uscsi_rqresid = ucmd->uscsi_rqlen - rqlen;
8952 			bcopy(ST_RQSENSE, un->un_srqbufp, rqlen);
8953 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8954 			    "st_decode_sense: stat=0x%x resid=0x%x\n",
8955 			    ucmd->uscsi_rqstatus, ucmd->uscsi_rqresid);
8956 		}
8957 	}
8958 
8959 	/*
8960 	 * If the drive is an MT-02, reposition the
8961 	 * secondary error code into the proper place.
8962 	 *
8963 	 * XXX	MT-02 is non-CCS tape, so secondary error code
8964 	 * is in byte 8.  However, in SCSI-2, tape has CCS definition
8965 	 * so it's in byte 12.
8966 	 */
8967 	if (un->un_dp->type == ST_TYPE_EMULEX) {
8968 		sensep->es_code = sensep->es_add_info[0];
8969 	}
8970 
8971 	ST_CDB(ST_DEVINFO, "st_decode_sense failed CDB",
8972 	    (caddr_t)&CDBP(pkt)->scc_cmd);
8973 
8974 	ST_SENSE(ST_DEVINFO, "st_decode_sense sense data", (caddr_t)sensep,
8975 	    sizeof (*sensep));
8976 
8977 	/* for normal I/O check extract the resid values. */
8978 	if (bp != un->un_sbufp) {
8979 		if (sensep->es_valid) {
8980 			resid =
8981 			    (sensep->es_info_1 << 24) |
8982 			    (sensep->es_info_2 << 16) |
8983 			    (sensep->es_info_3 << 8)  |
8984 			    (sensep->es_info_4);
8985 			/* If fixed block */
8986 			if (un->un_bsize) {
8987 				resid *= un->un_bsize;
8988 			}
8989 		} else if (pkt->pkt_state & STATE_XFERRED_DATA) {
8990 			resid = pkt->pkt_resid;
8991 		} else {
8992 			resid = bp->b_bcount;
8993 		}
8994 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8995 		    "st_handle_sense (rw): xferred bit = %d, resid=%ld (%d), "
8996 		    "pkt_resid=%ld\n", pkt->pkt_state & STATE_XFERRED_DATA,
8997 		    resid,
8998 		    (sensep->es_info_1 << 24) |
8999 		    (sensep->es_info_2 << 16) |
9000 		    (sensep->es_info_3 << 8)  |
9001 		    (sensep->es_info_4),
9002 		    pkt->pkt_resid);
9003 		/*
9004 		 * The problem is, what should we believe?
9005 		 */
9006 		if (resid && (pkt->pkt_resid == 0)) {
9007 			pkt->pkt_resid = resid;
9008 		}
9009 	} else {
9010 		/*
9011 		 * If the command is SCMD_SPACE, we need to get the
9012 		 * residual as returned in the sense data, to adjust
9013 		 * our idea of current tape position correctly
9014 		 */
9015 		if ((CDBP(pkt)->scc_cmd == SCMD_LOCATE) ||
9016 		    (CDBP(pkt)->scc_cmd == SCMD_LOCATE_G4) ||
9017 		    (CDBP(pkt)->scc_cmd == SCMD_SPACE) ||
9018 		    (CDBP(pkt)->scc_cmd == SCMD_WRITE_FILE_MARK) &&
9019 		    (sensep->es_valid)) {
9020 			resid =
9021 			    (sensep->es_info_1 << 24) |
9022 			    (sensep->es_info_2 << 16) |
9023 			    (sensep->es_info_3 << 8)  |
9024 			    (sensep->es_info_4);
9025 			bp->b_resid = resid;
9026 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9027 			    "st_handle_sense(other):	resid=%ld\n", resid);
9028 		} else {
9029 			/*
9030 			 * If the special command is SCMD_READ,
9031 			 * the correct resid will be set later.
9032 			 */
9033 			resid = bp->b_bcount;
9034 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9035 			    "st_handle_sense(special read):  resid=%ld\n",
9036 			    resid);
9037 		}
9038 	}
9039 
9040 	if ((un->un_state >= ST_STATE_OPEN) &&
9041 	    (DEBUGGING || st_error_level == SCSI_ERR_ALL)) {
9042 		st_print_cdb(ST_DEVINFO, st_label, CE_NOTE,
9043 		    "Failed CDB", (char *)pkt->pkt_cdbp);
9044 		st_clean_print(ST_DEVINFO, st_label, CE_CONT,
9045 		    "sense data", (char *)sensep, amt);
9046 		scsi_log(ST_DEVINFO, st_label, CE_CONT,
9047 		    "count 0x%lx resid 0x%lx pktresid 0x%lx\n",
9048 		    bp->b_bcount, resid, pkt->pkt_resid);
9049 	}
9050 
9051 	switch (un->un_status = sensep->es_key) {
9052 	case KEY_NO_SENSE:
9053 		severity = SCSI_ERR_INFO;
9054 
9055 		/*
9056 		 * Erase, locate or rewind operation in progress, retry
9057 		 * ASC  ASCQ
9058 		 *  00   18    Erase operation in progress
9059 		 *  00   19    Locate operation in progress
9060 		 *  00   1A    Rewind operation in progress
9061 		 */
9062 		if (sensep->es_add_code == 0 &&
9063 		    ((sensep->es_qual_code == 0x18) ||
9064 		    (sensep->es_qual_code == 0x19) ||
9065 		    (sensep->es_qual_code == 0x1a))) {
9066 			rval = QUE_COMMAND;
9067 			break;
9068 		}
9069 
9070 		goto common;
9071 
9072 	case KEY_RECOVERABLE_ERROR:
9073 		severity = SCSI_ERR_RECOVERED;
9074 		if ((sensep->es_class == CLASS_EXTENDED_SENSE) &&
9075 		    (sensep->es_code == ST_DEFERRED_ERROR)) {
9076 			if (un->un_dp->options &
9077 			    ST_RETRY_ON_RECOVERED_DEFERRED_ERROR) {
9078 				rval = QUE_LAST_COMMAND;
9079 				scsi_errmsg(ST_SCSI_DEVP, pkt, st_label,
9080 				    severity, un->un_pos.lgclblkno,
9081 				    un->un_err_pos.lgclblkno, scsi_cmds,
9082 				    sensep);
9083 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
9084 				    "Command will be retried\n");
9085 			} else {
9086 				severity = SCSI_ERR_FATAL;
9087 				rval = COMMAND_DONE_ERROR_RECOVERED;
9088 				ST_DO_ERRSTATS(un, st_softerrs);
9089 				scsi_errmsg(ST_SCSI_DEVP, pkt, st_label,
9090 				    severity, un->un_pos.lgclblkno,
9091 				    un->un_err_pos.lgclblkno, scsi_cmds,
9092 				    sensep);
9093 			}
9094 			break;
9095 		}
9096 common:
9097 		/*
9098 		 * XXX only want reads to be stopped by filemarks.
9099 		 * Don't want them to be stopped by EOT.  EOT matters
9100 		 * only on write.
9101 		 */
9102 		if (sensep->es_filmk && !sensep->es_eom) {
9103 			rval = COMMAND_DONE;
9104 		} else if (sensep->es_eom) {
9105 			rval = COMMAND_DONE;
9106 		} else if (sensep->es_ili) {
9107 			/*
9108 			 * Fun with variable length record devices:
9109 			 * for specifying larger blocks sizes than the
9110 			 * actual physical record size.
9111 			 */
9112 			if (un->un_bsize == 0 && resid > 0) {
9113 				/*
9114 				 * XXX! Ugly.
9115 				 * The requested blocksize is > tape blocksize,
9116 				 * so this is ok, so we just return the
9117 				 * actual size xferred.
9118 				 */
9119 				pkt->pkt_resid = resid;
9120 				rval = COMMAND_DONE;
9121 			} else if (un->un_bsize == 0 && resid < 0) {
9122 				/*
9123 				 * The requested blocksize is < tape blocksize,
9124 				 * so this is not ok, so we err with ENOMEM
9125 				 */
9126 				rval = COMMAND_DONE_ERROR_RECOVERED;
9127 				st_bioerror(bp, ENOMEM);
9128 			} else {
9129 				ST_DO_ERRSTATS(un, st_softerrs);
9130 				severity = SCSI_ERR_FATAL;
9131 				rval = COMMAND_DONE_ERROR;
9132 				st_bioerror(bp, EINVAL);
9133 			}
9134 		} else {
9135 			/*
9136 			 * we hope and pray for this just being
9137 			 * something we can ignore (ie. a
9138 			 * truly recoverable soft error)
9139 			 */
9140 			rval = COMMAND_DONE;
9141 		}
9142 		if (sensep->es_filmk) {
9143 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9144 			    "filemark\n");
9145 			un->un_status = SUN_KEY_EOF;
9146 			un->un_pos.eof = ST_EOF_PENDING;
9147 			SET_PE_FLAG(un);
9148 		}
9149 
9150 		/*
9151 		 * ignore eom when reading, a fmk should terminate reading
9152 		 */
9153 		if ((sensep->es_eom) &&
9154 		    (CDBP(pkt)->scc_cmd != SCMD_READ)) {
9155 			if ((sensep->es_add_code == 0) &&
9156 			    (sensep->es_qual_code == 4)) {
9157 				ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9158 				    "bot\n");
9159 				un->un_status = SUN_KEY_BOT;
9160 				un->un_pos.eof = ST_NO_EOF;
9161 				un->un_pos.lgclblkno = 0;
9162 				un->un_pos.fileno = 0;
9163 				un->un_pos.blkno = 0;
9164 				un->un_pos.pmode = legacy;
9165 			} else {
9166 				ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9167 				    "eom\n");
9168 				un->un_status = SUN_KEY_EOT;
9169 				un->un_pos.eof = ST_EOM;
9170 			}
9171 			SET_PE_FLAG(un);
9172 		}
9173 
9174 		break;
9175 
9176 	case KEY_ILLEGAL_REQUEST:
9177 
9178 		if (un->un_laststate >= ST_STATE_OPEN) {
9179 			ST_DO_ERRSTATS(un, st_softerrs);
9180 			severity = SCSI_ERR_FATAL;
9181 		} else {
9182 			severity = SCSI_ERR_INFO;
9183 		}
9184 		break;
9185 
9186 	case KEY_MEDIUM_ERROR:
9187 		ST_DO_ERRSTATS(un, st_harderrs);
9188 		severity = SCSI_ERR_FATAL;
9189 
9190 		/*
9191 		 * for (buffered) writes, a medium error must be fatal
9192 		 */
9193 		if (CDBP(pkt)->scc_cmd != SCMD_WRITE) {
9194 			rval = COMMAND_DONE_ERROR_RECOVERED;
9195 		}
9196 
9197 check_keys:
9198 		/*
9199 		 * attempt to process the keys in the presence of
9200 		 * other errors
9201 		 */
9202 		if (sensep->es_ili && rval != COMMAND_DONE_ERROR) {
9203 			/*
9204 			 * Fun with variable length record devices:
9205 			 * for specifying larger blocks sizes than the
9206 			 * actual physical record size.
9207 			 */
9208 			if (un->un_bsize == 0 && resid > 0) {
9209 				/*
9210 				 * XXX! Ugly
9211 				 */
9212 				pkt->pkt_resid = resid;
9213 			} else if (un->un_bsize == 0 && resid < 0) {
9214 				st_bioerror(bp, EINVAL);
9215 			} else {
9216 				severity = SCSI_ERR_FATAL;
9217 				rval = COMMAND_DONE_ERROR;
9218 				st_bioerror(bp, EINVAL);
9219 			}
9220 		}
9221 		if (sensep->es_filmk) {
9222 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9223 			    "filemark\n");
9224 			un->un_status = SUN_KEY_EOF;
9225 			un->un_pos.eof = ST_EOF_PENDING;
9226 			SET_PE_FLAG(un);
9227 		}
9228 
9229 		/*
9230 		 * ignore eom when reading, a fmk should terminate reading
9231 		 */
9232 		if ((sensep->es_eom) &&
9233 		    (CDBP(pkt)->scc_cmd != SCMD_READ)) {
9234 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "eom\n");
9235 			un->un_status = SUN_KEY_EOT;
9236 			un->un_pos.eof = ST_EOM;
9237 			SET_PE_FLAG(un);
9238 		}
9239 
9240 		break;
9241 
9242 	case KEY_VOLUME_OVERFLOW:
9243 		ST_DO_ERRSTATS(un, st_softerrs);
9244 		un->un_pos.eof = ST_EOM;
9245 		severity = SCSI_ERR_FATAL;
9246 		rval = COMMAND_DONE_ERROR;
9247 		goto check_keys;
9248 
9249 	case KEY_HARDWARE_ERROR:
9250 		ST_DO_ERRSTATS(un, st_harderrs);
9251 		severity = SCSI_ERR_FATAL;
9252 		rval = COMMAND_DONE_ERROR;
9253 		if (un->un_dp->options & ST_EJECT_ON_CHANGER_FAILURE)
9254 			un->un_eject_tape_on_failure = st_check_asc_ascq(un);
9255 		break;
9256 
9257 	case KEY_BLANK_CHECK:
9258 		ST_DO_ERRSTATS(un, st_softerrs);
9259 		severity = SCSI_ERR_INFO;
9260 
9261 		/*
9262 		 * if not a special request and some data was xferred then it
9263 		 * it is not an error yet
9264 		 */
9265 		if (bp != un->un_sbufp && (bp->b_flags & B_READ)) {
9266 			/*
9267 			 * no error for read with or without data xferred
9268 			 */
9269 			un->un_status = SUN_KEY_EOT;
9270 			un->un_pos.eof = ST_EOT;
9271 			rval = COMMAND_DONE_ERROR;
9272 			SET_PE_FLAG(un);
9273 			goto check_keys;
9274 		} else if (bp != un->un_sbufp &&
9275 		    (pkt->pkt_state & STATE_XFERRED_DATA)) {
9276 			rval = COMMAND_DONE;
9277 		} else {
9278 			rval = COMMAND_DONE_ERROR_RECOVERED;
9279 		}
9280 
9281 		if (un->un_laststate >= ST_STATE_OPEN) {
9282 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9283 			    "blank check\n");
9284 			un->un_pos.eof = ST_EOM;
9285 		}
9286 		if ((CDBP(pkt)->scc_cmd == SCMD_LOCATE) ||
9287 		    (CDBP(pkt)->scc_cmd == SCMD_LOCATE_G4) ||
9288 		    (CDBP(pkt)->scc_cmd == SCMD_SPACE) &&
9289 		    (un->un_dp->options & ST_KNOWS_EOD)) {
9290 			/*
9291 			 * we were doing a fast forward by skipping
9292 			 * multiple fmk at the time
9293 			 */
9294 			st_bioerror(bp, EIO);
9295 			severity = SCSI_ERR_RECOVERED;
9296 			rval	 = COMMAND_DONE;
9297 		}
9298 		SET_PE_FLAG(un);
9299 		goto check_keys;
9300 
9301 	case KEY_WRITE_PROTECT:
9302 		if (st_wrongtapetype(un)) {
9303 			un->un_status = SUN_KEY_WRONGMEDIA;
9304 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9305 		"wrong tape for writing- use DC6150 tape (or equivalent)\n");
9306 			severity = SCSI_ERR_UNKNOWN;
9307 		} else {
9308 			severity = SCSI_ERR_FATAL;
9309 		}
9310 		ST_DO_ERRSTATS(un, st_harderrs);
9311 		rval = COMMAND_DONE_ERROR;
9312 		st_bioerror(bp, EACCES);
9313 		break;
9314 
9315 	case KEY_UNIT_ATTENTION:
9316 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9317 		    "KEY_UNIT_ATTENTION : un_state = %d\n", un->un_state);
9318 
9319 		/*
9320 		 * If we have detected a Bus Reset and the tape
9321 		 * drive has been reserved.
9322 		 */
9323 		if (ST_RQSENSE->es_add_code == 0x29 &&
9324 		    (un->un_rsvd_status & ST_RESERVE)) {
9325 			un->un_rsvd_status |= ST_LOST_RESERVE;
9326 			ST_DEBUG(ST_DEVINFO, st_label, CE_WARN,
9327 			    "st_decode_sense: Lost Reservation\n");
9328 		}
9329 
9330 		if (un->un_state <= ST_STATE_OPENING) {
9331 			/*
9332 			 * Look, the tape isn't open yet, now determine
9333 			 * if the cause is a BUS RESET, Save the file and
9334 			 * Block positions for the callers to recover from
9335 			 * the loss of position.
9336 			 */
9337 			if (un->un_pos.pmode != invalid) {
9338 				if (ST_RQSENSE->es_add_code == 0x29) {
9339 					un->un_save_fileno = un->un_pos.fileno;
9340 					un->un_save_blkno = un->un_pos.blkno;
9341 					un->un_restore_pos = 1;
9342 				}
9343 			}
9344 
9345 			if ((int)un->un_retry_ct++ < st_retry_count) {
9346 				rval = QUE_COMMAND;
9347 			} else {
9348 				rval = COMMAND_DONE_ERROR;
9349 			}
9350 			severity = SCSI_ERR_INFO;
9351 
9352 		} else {
9353 			/*
9354 			 * Check if it is an Unexpected Unit Attention.
9355 			 * If state is >= ST_STATE_OPEN, we have
9356 			 * already done the initialization .
9357 			 * In this case it is Fatal Error
9358 			 * since no further reading/writing
9359 			 * can be done with fileno set to < 0.
9360 			 */
9361 			if (un->un_state >= ST_STATE_OPEN) {
9362 				ST_DO_ERRSTATS(un, st_harderrs);
9363 				severity = SCSI_ERR_FATAL;
9364 			} else {
9365 				severity = SCSI_ERR_INFO;
9366 			}
9367 			rval = COMMAND_DONE_ERROR;
9368 		}
9369 		un->un_pos.pmode = invalid;
9370 
9371 		break;
9372 
9373 	case KEY_NOT_READY:
9374 		/*
9375 		 * If in process of getting ready retry.
9376 		 */
9377 		if (sensep->es_add_code  == 0x04 &&
9378 		    sensep->es_qual_code == 0x01 &&
9379 		    un->un_retry_ct++ < st_retry_count) {
9380 			rval = QUE_COMMAND;
9381 			severity = SCSI_ERR_INFO;
9382 		} else {
9383 			/* give up */
9384 			rval = COMMAND_DONE_ERROR;
9385 			severity = SCSI_ERR_FATAL;
9386 		}
9387 
9388 		/*
9389 		 * If this was an error and after device opened
9390 		 * do error stats.
9391 		 */
9392 		if (rval == COMMAND_DONE_ERROR &&
9393 		    un->un_state > ST_STATE_OPENING) {
9394 			ST_DO_ERRSTATS(un, st_harderrs);
9395 		}
9396 
9397 		if (ST_RQSENSE->es_add_code == 0x3a) {
9398 			if (st_error_level >= SCSI_ERR_FATAL)
9399 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
9400 				    "Tape not inserted in drive\n");
9401 			un->un_mediastate = MTIO_EJECTED;
9402 			cv_broadcast(&un->un_state_cv);
9403 		}
9404 		if ((un->un_dp->options & ST_EJECT_ON_CHANGER_FAILURE) &&
9405 		    (rval != QUE_COMMAND))
9406 			un->un_eject_tape_on_failure = st_check_asc_ascq(un);
9407 		break;
9408 
9409 	case KEY_ABORTED_COMMAND:
9410 
9411 		/*
9412 		 * Probably a parity error...
9413 		 * if we retry here then this may cause data to be
9414 		 * written twice or data skipped during reading
9415 		 */
9416 		ST_DO_ERRSTATS(un, st_harderrs);
9417 		severity = SCSI_ERR_FATAL;
9418 		rval = COMMAND_DONE_ERROR;
9419 		goto check_keys;
9420 
9421 	default:
9422 		/*
9423 		 * Undecoded sense key.	 Try retries and hope
9424 		 * that will fix the problem.  Otherwise, we're
9425 		 * dead.
9426 		 */
9427 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9428 		    "Unhandled Sense Key '%s'\n",
9429 		    sense_keys[un->un_status]);
9430 		ST_DO_ERRSTATS(un, st_harderrs);
9431 		severity = SCSI_ERR_FATAL;
9432 		rval = COMMAND_DONE_ERROR;
9433 		goto check_keys;
9434 	}
9435 
9436 	if ((!(pkt->pkt_flags & FLAG_SILENT) &&
9437 	    un->un_state >= ST_STATE_OPEN) && (DEBUGGING ||
9438 	    (un->un_laststate > ST_STATE_OPENING) &&
9439 	    (severity >= st_error_level))) {
9440 
9441 		scsi_errmsg(ST_SCSI_DEVP, pkt, st_label, severity,
9442 		    un->un_pos.lgclblkno, un->un_err_pos.lgclblkno,
9443 		    scsi_cmds, sensep);
9444 		if (sensep->es_filmk) {
9445 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
9446 			    "File Mark Detected\n");
9447 		}
9448 		if (sensep->es_eom) {
9449 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
9450 			    "End-of-Media Detected\n");
9451 		}
9452 		if (sensep->es_ili) {
9453 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
9454 			    "Incorrect Length Indicator Set\n");
9455 		}
9456 	}
9457 	get_error = geterror(bp);
9458 	if (((rval == COMMAND_DONE_ERROR) ||
9459 	    (rval == COMMAND_DONE_ERROR_RECOVERED)) &&
9460 	    ((get_error == EIO) || (get_error == 0))) {
9461 		un->un_rqs_state |= (ST_RQS_ERROR | ST_RQS_VALID);
9462 		bcopy(ST_RQSENSE, un->un_uscsi_rqs_buf, SENSE_LENGTH);
9463 		if (un->un_rqs_state & ST_RQS_READ) {
9464 			un->un_rqs_state &= ~(ST_RQS_READ);
9465 		} else {
9466 			un->un_rqs_state |= ST_RQS_OVR;
9467 		}
9468 	}
9469 
9470 	return (rval);
9471 }
9472 
9473 
9474 static int
9475 st_handle_intr_retry_lcmd(struct scsi_tape *un, struct buf *bp)
9476 {
9477 	int status = TRAN_ACCEPT;
9478 
9479 	mutex_enter(ST_MUTEX);
9480 
9481 	ST_FUNC(ST_DEVINFO, st_handle_intr_retry_lcmd);
9482 
9483 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9484 	    "st_handle_intr_rtr_lcmd(), un = 0x%p\n", (void *)un);
9485 
9486 	/*
9487 	 * Check to see if we hit the retry timeout. We check to make sure
9488 	 * this is the first one on the runq and make sure we have not
9489 	 * queued up any more, so this one has to be the last on the list
9490 	 * also. If it is not, we have to fail.  If it is not the first, but
9491 	 * is the last we are in trouble anyway, as we are in the interrupt
9492 	 * context here.
9493 	 */
9494 	if (((int)un->un_retry_ct > st_retry_count) ||
9495 	    ((un->un_runqf != bp) && (un->un_runql != bp))) {
9496 		goto exit;
9497 	}
9498 
9499 	if (un->un_throttle) {
9500 		un->un_last_throttle = un->un_throttle;
9501 		un->un_throttle = 0;
9502 	}
9503 
9504 	/*
9505 	 * Here we know : bp is the first and last one on the runq
9506 	 * it is not necessary to put it back on the head of the
9507 	 * waitq and then move from waitq to runq. Save this queuing
9508 	 * and call scsi_transport.
9509 	 */
9510 
9511 	mutex_exit(ST_MUTEX);
9512 
9513 	status = scsi_transport(BP_PKT(bp));
9514 
9515 	mutex_enter(ST_MUTEX);
9516 
9517 	if (status == TRAN_ACCEPT) {
9518 		un->un_tran_retry_ct = 0;
9519 		if (un->un_last_throttle) {
9520 			un->un_throttle = un->un_last_throttle;
9521 		}
9522 		mutex_exit(ST_MUTEX);
9523 
9524 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9525 		    "restart transport \n");
9526 		return (0);
9527 	}
9528 
9529 	ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
9530 	mutex_exit(ST_MUTEX);
9531 
9532 	if (status == TRAN_BUSY) {
9533 		if (st_handle_intr_busy(un, bp, ST_TRAN_BUSY_TIMEOUT) == 0) {
9534 			return (0);
9535 		}
9536 	}
9537 	ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9538 	    "restart transport rejected\n");
9539 	mutex_enter(ST_MUTEX);
9540 	ST_DO_ERRSTATS(un, st_transerrs);
9541 	if (un->un_last_throttle) {
9542 		un->un_throttle = un->un_last_throttle;
9543 	}
9544 exit:
9545 	mutex_exit(ST_MUTEX);
9546 	return (-1);
9547 }
9548 
9549 static int
9550 st_wrongtapetype(struct scsi_tape *un)
9551 {
9552 
9553 	ST_FUNC(ST_DEVINFO, st_wrongtapetype);
9554 
9555 	ASSERT(mutex_owned(ST_MUTEX));
9556 
9557 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_wrongtapetype()\n");
9558 
9559 	/*
9560 	 * Hack to handle  600A, 600XTD, 6150 && 660 vs. 300XL tapes...
9561 	 */
9562 	if (un->un_dp && (un->un_dp->options & ST_QIC) && un->un_mspl) {
9563 		switch (un->un_dp->type) {
9564 		case ST_TYPE_WANGTEK:
9565 		case ST_TYPE_ARCHIVE:
9566 			/*
9567 			 * If this really worked, we could go off of
9568 			 * the density codes set in the modesense
9569 			 * page. For this drive, 0x10 == QIC-120,
9570 			 * 0xf == QIC-150, and 0x5 should be for
9571 			 * both QIC-24 and, maybe, QIC-11. However,
9572 			 * the h/w doesn't do what the manual says
9573 			 * that it should, so we'll key off of
9574 			 * getting a WRITE PROTECT error AND wp *not*
9575 			 * set in the mode sense information.
9576 			 */
9577 			/*
9578 			 * XXX but we already know that status is
9579 			 * write protect, so don't check it again.
9580 			 */
9581 
9582 			if (un->un_status == KEY_WRITE_PROTECT &&
9583 			    un->un_mspl->wp == 0) {
9584 				return (1);
9585 			}
9586 			break;
9587 		default:
9588 			break;
9589 		}
9590 	}
9591 	return (0);
9592 }
9593 
9594 static int
9595 st_check_error(struct scsi_tape *un, struct scsi_pkt *pkt)
9596 {
9597 	int action;
9598 
9599 	ST_FUNC(ST_DEVINFO, st_check_error);
9600 
9601 	ASSERT(mutex_owned(ST_MUTEX));
9602 
9603 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_check_error()\n");
9604 
9605 	if (SCBP_C(pkt) == STATUS_RESERVATION_CONFLICT) {
9606 		action = COMMAND_DONE_EACCES;
9607 		un->un_rsvd_status |= ST_RESERVATION_CONFLICT;
9608 	} else if (SCBP(pkt)->sts_busy) {
9609 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG, "unit busy\n");
9610 		if ((int)un->un_retry_ct++ < st_retry_count) {
9611 			action = QUE_BUSY_COMMAND;
9612 		} else if ((un->un_rsvd_status &
9613 		    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
9614 			/*
9615 			 * If this is a command done before reserve is done
9616 			 * don't reset.
9617 			 */
9618 			action = COMMAND_DONE_ERROR;
9619 		} else {
9620 			ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
9621 			    "unit busy too long\n");
9622 			mutex_exit(ST_MUTEX);
9623 			if (scsi_reset(ROUTE, RESET_TARGET) == 0) {
9624 				(void) scsi_reset(ROUTE, RESET_ALL);
9625 			}
9626 			mutex_enter(ST_MUTEX);
9627 			action = COMMAND_DONE_ERROR;
9628 		}
9629 	} else if (SCBP(pkt)->sts_chk) {
9630 		/*
9631 		 * we should only get here if the auto rqsense failed
9632 		 * thru a uscsi cmd without autorequest sense
9633 		 * so we just try again
9634 		 */
9635 		action = QUE_SENSE;
9636 	} else {
9637 		action = COMMAND_DONE;
9638 	}
9639 	return (action);
9640 }
9641 
9642 static void
9643 st_calc_bnum(struct scsi_tape *un, struct buf *bp)
9644 {
9645 	int nblks;
9646 
9647 	ST_FUNC(ST_DEVINFO, st_calc_bnum);
9648 
9649 	ASSERT(mutex_owned(ST_MUTEX));
9650 
9651 	/* If variable block mode */
9652 	if (un->un_bsize == 0) {
9653 		nblks = ((bp->b_bcount - bp->b_resid  == 0) ? 0 : 1);
9654 		un->un_kbytes_xferred += (bp->b_bcount - bp->b_resid) / ONE_K;
9655 	} else {
9656 		nblks = ((bp->b_bcount - bp->b_resid) / un->un_bsize);
9657 		un->un_kbytes_xferred += (nblks * un->un_bsize) / ONE_K;
9658 	}
9659 	un->un_pos.blkno += nblks;
9660 	un->un_pos.lgclblkno += nblks;
9661 }
9662 
9663 static void
9664 st_set_state(struct scsi_tape *un)
9665 {
9666 	struct buf *bp = un->un_runqf;
9667 	struct scsi_pkt *sp = BP_PKT(bp);
9668 	struct uscsi_cmd *ucmd;
9669 
9670 	ST_FUNC(ST_DEVINFO, st_set_state);
9671 
9672 	ASSERT(mutex_owned(ST_MUTEX));
9673 
9674 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9675 	    "st_set_state(): eof=%x	fmneeded=%x  pkt_resid=0x%lx (%ld)\n",
9676 	    un->un_pos.eof, un->un_fmneeded, sp->pkt_resid, sp->pkt_resid);
9677 
9678 	if (bp != un->un_sbufp) {
9679 #ifdef STDEBUG
9680 		if (DEBUGGING && sp->pkt_resid) {
9681 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9682 			    "pkt_resid %ld bcount %ld\n",
9683 			    sp->pkt_resid, bp->b_bcount);
9684 		}
9685 #endif
9686 		bp->b_resid = sp->pkt_resid;
9687 		st_calc_bnum(un, bp);
9688 		if (bp->b_flags & B_READ) {
9689 			un->un_lastop = ST_OP_READ;
9690 			un->un_fmneeded = 0;
9691 		} else {
9692 			un->un_lastop = ST_OP_WRITE;
9693 			if (un->un_dp->options & ST_REEL) {
9694 				un->un_fmneeded = 2;
9695 			} else {
9696 				un->un_fmneeded = 1;
9697 			}
9698 		}
9699 		/*
9700 		 * all is honky dory at this point, so let's
9701 		 * readjust the throttle, to increase speed, if we
9702 		 * have not throttled down.
9703 		 */
9704 		if (un->un_throttle) {
9705 			un->un_throttle = un->un_max_throttle;
9706 		}
9707 	} else {
9708 		optype new_lastop;
9709 		uchar_t cmd = (uchar_t)(intptr_t)bp->b_forw;
9710 
9711 		un->un_lastop = ST_OP_CTL;
9712 
9713 		switch (cmd) {
9714 		case SCMD_WRITE:
9715 			bp->b_resid = sp->pkt_resid;
9716 			new_lastop = ST_OP_WRITE;
9717 			st_calc_bnum(un, bp);
9718 			if (un->un_dp->options & ST_REEL) {
9719 				un->un_fmneeded = 2;
9720 			} else {
9721 				un->un_fmneeded = 1;
9722 			}
9723 			break;
9724 		case SCMD_READ:
9725 			bp->b_resid = sp->pkt_resid;
9726 			new_lastop = ST_OP_READ;
9727 			st_calc_bnum(un, bp);
9728 			un->un_fmneeded = 0;
9729 			break;
9730 		case SCMD_WRITE_FILE_MARK:
9731 		{
9732 			int fmdone;
9733 
9734 			if (un->un_pos.eof != ST_EOM) {
9735 				un->un_pos.eof = ST_NO_EOF;
9736 			}
9737 			fmdone = (bp->b_bcount - bp->b_resid);
9738 			if (fmdone > 0) {
9739 				un->un_lastop = new_lastop = ST_OP_WEOF;
9740 				un->un_pos.lgclblkno += fmdone;
9741 				un->un_pos.fileno += fmdone;
9742 				un->un_pos.blkno = 0;
9743 			} else {
9744 				new_lastop = ST_OP_CTL;
9745 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
9746 				    "Flushed buffer\n");
9747 			}
9748 			if (fmdone > un->un_fmneeded) {
9749 				un->un_fmneeded = 0;
9750 			} else {
9751 				un->un_fmneeded -= fmdone;
9752 			}
9753 			break;
9754 		}
9755 		case SCMD_REWIND:
9756 			un->un_pos.eof = ST_NO_EOF;
9757 			un->un_pos.fileno = 0;
9758 			un->un_pos.blkno = 0;
9759 			un->un_pos.lgclblkno = 0;
9760 			un->un_pos.pmode = legacy;
9761 			new_lastop = ST_OP_CTL;
9762 			break;
9763 
9764 		case SCMD_SPACE:
9765 		{
9766 			int count;
9767 			long resid;
9768 			int done;
9769 
9770 			count = (int)SPACE_CNT(bp->b_bcount);
9771 			/* if was a uscsi space cmd b_bcount == 0 */
9772 			if (count == 0) {
9773 				count =
9774 				    (sp->pkt_cdbp[2] << 16) |
9775 				    (sp->pkt_cdbp[3] << 8)  |
9776 				    (sp->pkt_cdbp[4]);
9777 			}
9778 			resid = (long)SPACE_CNT(bp->b_resid);
9779 			if (count >= 0) {
9780 				done = (count - resid);
9781 			} else {
9782 				done = ((-count) - resid);
9783 			}
9784 			if (done > 0) {
9785 				un->un_lastop = new_lastop = ST_OP_CTL;
9786 			} else {
9787 				new_lastop = ST_OP_CTL;
9788 			}
9789 
9790 			ST_SPAC(ST_DEVINFO, st_label, SCSI_DEBUG,
9791 			    "space cmd: cdb[1] = %s\n"
9792 			    "space data:       = 0x%lx\n"
9793 			    "space count:      = %d\n"
9794 			    "space resid:      = %ld\n"
9795 			    "spaces done:      = %d\n"
9796 			    "fileno before     = %d\n"
9797 			    "blkno before      = %d\n",
9798 			    space_strs[sp->pkt_cdbp[1] & 7],
9799 			    bp->b_bcount,
9800 			    count, resid, done,
9801 			    un->un_pos.fileno, un->un_pos.blkno);
9802 
9803 			switch (sp->pkt_cdbp[1]) {
9804 			case SPACE_TYPE(SP_FLM):
9805 				/* Space file forward */
9806 				if (count >= 0) {
9807 					if (un->un_pos.eof <= ST_EOF) {
9808 						un->un_pos.eof = ST_NO_EOF;
9809 					}
9810 					un->un_pos.fileno += done;
9811 					un->un_pos.blkno = 0;
9812 					break;
9813 				}
9814 				/* Space file backward */
9815 				if (done > un->un_pos.fileno) {
9816 					un->un_pos.fileno = 0;
9817 					un->un_pos.blkno = 0;
9818 				} else {
9819 					un->un_pos.fileno -= done;
9820 					un->un_pos.blkno = INF;
9821 				}
9822 				break;
9823 			case SPACE_TYPE(SP_BLK):
9824 				/* Space block forward */
9825 				if (count >= 0) {
9826 					un->un_pos.blkno += done;
9827 					break;
9828 				}
9829 				/* Space block backward */
9830 				if (un->un_pos.eof >= ST_EOF_PENDING) {
9831 				/*
9832 				 * we stepped back into
9833 				 * a previous file; we are not
9834 				 * making an effort to pretend that
9835 				 * we are still in the current file
9836 				 * ie. logical == physical position
9837 				 * and leave it to st_ioctl to correct
9838 				 */
9839 					if (done > un->un_pos.blkno) {
9840 						un->un_pos.blkno = 0;
9841 					} else {
9842 						un->un_pos.fileno--;
9843 						un->un_pos.blkno = INF;
9844 					}
9845 				} else {
9846 					un->un_pos.blkno -= done;
9847 				}
9848 				break;
9849 			case SPACE_TYPE(SP_SQFLM):
9850 				un->un_pos.pmode = logical;
9851 				un->un_pos.blkno = 0;
9852 				un->un_lastop = new_lastop = ST_OP_CTL;
9853 				break;
9854 			case SPACE_TYPE(SP_EOD):
9855 				un->un_pos.pmode = logical;
9856 				un->un_pos.eof = ST_EOM;
9857 				un->un_status = KEY_BLANK_CHECK;
9858 				break;
9859 			default:
9860 				un->un_pos.pmode = invalid;
9861 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
9862 				    "Unsupported space cmd: %s\n",
9863 				    space_strs[sp->pkt_cdbp[1] & 7]);
9864 
9865 				un->un_lastop = new_lastop = ST_OP_CTL;
9866 			}
9867 
9868 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9869 			    "after_space rs %ld fil %d blk %d\n",
9870 			    resid, un->un_pos.fileno, un->un_pos.blkno);
9871 
9872 			break;
9873 		}
9874 		case SCMD_LOAD:
9875 			if ((bp->b_bcount & (LD_LOAD | LD_EOT)) == LD_LOAD) {
9876 				un->un_pos.fileno = 0;
9877 				un->un_pos.pmode = legacy;
9878 			} else {
9879 				un->un_state = ST_STATE_OFFLINE;
9880 				un->un_pos.pmode = invalid;
9881 			}
9882 			un->un_density_known = 0;
9883 			un->un_pos.eof = ST_NO_EOF;
9884 			un->un_pos.blkno = 0;
9885 			un->un_lastop = new_lastop = ST_OP_CTL;
9886 			break;
9887 		case SCMD_ERASE:
9888 			un->un_pos.eof = ST_NO_EOF;
9889 			un->un_pos.blkno = 0;
9890 			un->un_pos.fileno = 0;
9891 			un->un_pos.lgclblkno = 0;
9892 			un->un_pos.pmode = legacy;
9893 			new_lastop = ST_OP_CTL;
9894 			break;
9895 		case SCMD_RESERVE:
9896 			un->un_rsvd_status |= ST_RESERVE;
9897 			un->un_rsvd_status &=
9898 			    ~(ST_RELEASE | ST_LOST_RESERVE |
9899 			    ST_RESERVATION_CONFLICT);
9900 			new_lastop = un->un_lastop;
9901 			break;
9902 		case SCMD_RELEASE:
9903 			un->un_rsvd_status |= ST_RELEASE;
9904 			un->un_rsvd_status &=
9905 			    ~(ST_RESERVE | ST_LOST_RESERVE |
9906 			    ST_RESERVATION_CONFLICT);
9907 			new_lastop = ST_OP_CTL;
9908 			break;
9909 		case SCMD_PERSISTENT_RESERVE_IN:
9910 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9911 			    "PGR_IN command\n");
9912 			break;
9913 		case SCMD_PERSISTENT_RESERVE_OUT:
9914 			switch (sp->pkt_cdbp[1] & ST_SA_MASK) {
9915 			case ST_SA_SCSI3_RESERVE:
9916 			case ST_SA_SCSI3_PREEMPT:
9917 			case ST_SA_SCSI3_PREEMPTANDABORT:
9918 				un->un_rsvd_status |=
9919 				    ST_APPLICATION_RESERVATIONS;
9920 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9921 				    "PGR Reserve and set: entering"
9922 				    " ST_APPLICATION_RESERVATIONS mode");
9923 				break;
9924 			case ST_SA_SCSI3_RELEASE:
9925 			case ST_SA_SCSI3_CLEAR:
9926 				un->un_rsvd_status &=
9927 				    ~ST_APPLICATION_RESERVATIONS;
9928 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9929 				    "PGR Release and reset: exiting"
9930 				    " ST_APPLICATION_RESERVATIONS mode");
9931 				break;
9932 			}
9933 			break;
9934 		case SCMD_TEST_UNIT_READY:
9935 		case SCMD_READ_BLKLIM:
9936 		case SCMD_REQUEST_SENSE:
9937 		case SCMD_INQUIRY:
9938 		case SCMD_RECOVER_BUF:
9939 		case SCMD_MODE_SELECT:
9940 		case SCMD_MODE_SENSE:
9941 		case SCMD_DOORLOCK:
9942 		case SCMD_READ_BUFFER:
9943 		case SCMD_REPORT_DENSITIES:
9944 		case SCMD_LOG_SELECT_G1:
9945 		case SCMD_LOG_SENSE_G1:
9946 		case SCMD_REPORT_LUNS:
9947 		case SCMD_READ_ATTRIBUTE:
9948 		case SCMD_READ_MEDIA_SERIAL:
9949 			new_lastop = ST_OP_CTL;
9950 			break;
9951 		case SCMD_READ_POSITION:
9952 			new_lastop = ST_OP_CTL;
9953 			if (USCSI_CMD(bp)) {
9954 				(void) st_get_read_pos(un, bp);
9955 			}
9956 			break;
9957 		case SCMD_LOCATE:
9958 		case SCMD_LOCATE_G4:
9959 			/* Locate makes position mode no longer legacy */
9960 			un->un_lastop = new_lastop = ST_OP_CTL;
9961 			break;
9962 		default:
9963 			/*
9964 			 * Unknown command, If was USCSI and USCSI_SILENT
9965 			 * flag was not set, set position to unknown.
9966 			 */
9967 			if ((((ucmd = BP_UCMD(bp)) != NULL) &&
9968 			    (ucmd->uscsi_flags & USCSI_SILENT) == 0)) {
9969 				ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
9970 				    "unknown cmd 0x%X caused loss of state\n",
9971 				    cmd);
9972 			} else {
9973 				break;
9974 			}
9975 			/* FALLTHROUGH */
9976 		case SCMD_WRITE_BUFFER: /* Writes new firmware to device */
9977 			un->un_pos.pmode = invalid;
9978 			un->un_lastop = new_lastop = ST_OP_CTL;
9979 			break;
9980 		}
9981 
9982 		/* new_lastop should have been changed */
9983 		ASSERT(new_lastop != ST_OP_NIL);
9984 
9985 		/* If un_lastop should copy new_lastop  */
9986 		if (((un->un_lastop == ST_OP_WRITE) ||
9987 		    (un->un_lastop == ST_OP_WEOF)) &&
9988 		    new_lastop != ST_OP_CTL) {
9989 			un->un_lastop = new_lastop;
9990 		}
9991 	}
9992 
9993 	/*
9994 	 * In the st driver we have a logical and physical file position.
9995 	 * Under BSD behavior, when you get a zero read, the logical position
9996 	 * is before the filemark but after the last record of the file.
9997 	 * The physical position is after the filemark. MTIOCGET should always
9998 	 * return the logical file position.
9999 	 *
10000 	 * The next read gives a silent skip to the next file.
10001 	 * Under SVR4, the logical file position remains before the filemark
10002 	 * until the file is closed or a space operation is performed.
10003 	 * Hence set err_resid and err_file before changing fileno if case
10004 	 * BSD Behaviour.
10005 	 */
10006 	un->un_err_resid = bp->b_resid;
10007 	COPY_POS(&un->un_err_pos, &un->un_pos);
10008 	un->un_retry_ct = 0;
10009 
10010 
10011 	/*
10012 	 * If we've seen a filemark via the last read operation
10013 	 * advance the file counter, but mark things such that
10014 	 * the next read operation gets a zero count. We have
10015 	 * to put this here to handle the case of sitting right
10016 	 * at the end of a tape file having seen the file mark,
10017 	 * but the tape is closed and then re-opened without
10018 	 * any further i/o. That is, the position information
10019 	 * must be updated before a close.
10020 	 */
10021 
10022 	if (un->un_lastop == ST_OP_READ && un->un_pos.eof == ST_EOF_PENDING) {
10023 		/*
10024 		 * If we're a 1/2" tape, and we get a filemark
10025 		 * right on block 0, *AND* we were not in the
10026 		 * first file on the tape, and we've hit logical EOM.
10027 		 * We'll mark the state so that later we do the
10028 		 * right thing (in st_close(), st_strategy() or
10029 		 * st_ioctl()).
10030 		 *
10031 		 */
10032 		if ((un->un_dp->options & ST_REEL) &&
10033 		    !(un->un_dp->options & ST_READ_IGNORE_EOFS) &&
10034 		    un->un_pos.blkno == 0 && un->un_pos.fileno > 0) {
10035 			un->un_pos.eof = ST_EOT_PENDING;
10036 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10037 			    "eot pending\n");
10038 			un->un_pos.fileno++;
10039 			un->un_pos.blkno = 0;
10040 		} else if (BSD_BEHAVIOR) {
10041 			/*
10042 			 * If the read of the filemark was a side effect
10043 			 * of reading some blocks (i.e., data was actually
10044 			 * read), then the EOF mark is pending and the
10045 			 * bump into the next file awaits the next read
10046 			 * operation (which will return a zero count), or
10047 			 * a close or a space operation, else the bump
10048 			 * into the next file occurs now.
10049 			 */
10050 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10051 			    "resid=%lx, bcount=%lx\n",
10052 			    bp->b_resid, bp->b_bcount);
10053 
10054 			if (bp->b_resid != bp->b_bcount) {
10055 				un->un_pos.eof = ST_EOF;
10056 			} else {
10057 				un->un_silent_skip = 1;
10058 				un->un_pos.eof = ST_NO_EOF;
10059 				un->un_pos.fileno++;
10060 				un->un_pos.lgclblkno++;
10061 				un->un_save_blkno = un->un_pos.blkno;
10062 				un->un_pos.blkno = 0;
10063 			}
10064 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10065 			    "eof of file %d, eof=%d\n",
10066 			    un->un_pos.fileno, un->un_pos.eof);
10067 		} else if (SVR4_BEHAVIOR) {
10068 			/*
10069 			 * If the read of the filemark was a side effect
10070 			 * of reading some blocks (i.e., data was actually
10071 			 * read), then the next read should return 0
10072 			 */
10073 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10074 			    "resid=%lx, bcount=%lx\n",
10075 			    bp->b_resid, bp->b_bcount);
10076 			if (bp->b_resid == bp->b_bcount) {
10077 				un->un_pos.eof = ST_EOF;
10078 			}
10079 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10080 			    "eof of file=%d, eof=%d\n",
10081 			    un->un_pos.fileno, un->un_pos.eof);
10082 		}
10083 	}
10084 }
10085 
10086 /*
10087  * set the correct un_errno, to take corner cases into consideration
10088  */
10089 static void
10090 st_set_pe_errno(struct scsi_tape *un)
10091 {
10092 	ST_FUNC(ST_DEVINFO, st_set_pe_errno);
10093 
10094 	ASSERT(mutex_owned(ST_MUTEX));
10095 
10096 	/* if errno is already set, don't reset it */
10097 	if (un->un_errno)
10098 		return;
10099 
10100 	/* here un_errno == 0 */
10101 	/*
10102 	 * if the last transfer before flushing all the
10103 	 * waiting I/O's, was 0 (resid = count), then we
10104 	 * want to give the user an error on all the rest,
10105 	 * so here.  If there was a transfer, we set the
10106 	 * resid and counts to 0, and let it drop through,
10107 	 * giving a zero return.  the next I/O will then
10108 	 * give an error.
10109 	 */
10110 	if (un->un_last_resid == un->un_last_count) {
10111 		switch (un->un_pos.eof) {
10112 		case ST_EOM:
10113 			un->un_errno = ENOMEM;
10114 			break;
10115 		case ST_EOT:
10116 		case ST_EOF:
10117 			un->un_errno = EIO;
10118 			break;
10119 		}
10120 	} else {
10121 		/*
10122 		 * we know they did not have a zero, so make
10123 		 * sure they get one
10124 		 */
10125 		un->un_last_resid = un->un_last_count = 0;
10126 	}
10127 }
10128 
10129 
10130 /*
10131  * send in a marker pkt to terminate flushing of commands by BBA (via
10132  * flush-on-errors) property.  The HBA will always return TRAN_ACCEPT
10133  */
10134 static void
10135 st_hba_unflush(struct scsi_tape *un)
10136 {
10137 	ST_FUNC(ST_DEVINFO, st_hba_unflush);
10138 
10139 	ASSERT(mutex_owned(ST_MUTEX));
10140 
10141 	if (!un->un_flush_on_errors)
10142 		return;
10143 
10144 #ifdef FLUSH_ON_ERRORS
10145 
10146 	if (!un->un_mkr_pkt) {
10147 		un->un_mkr_pkt = scsi_init_pkt(ROUTE, NULL, (struct buf *)NULL,
10148 		    NULL, 0, 0, 0, SLEEP_FUNC, NULL);
10149 
10150 		/* we slept, so it must be there */
10151 		pkt->pkt_flags |= FLAG_FLUSH_MARKER;
10152 	}
10153 
10154 	mutex_exit(ST_MUTEX);
10155 	scsi_transport(un->un_mkr_pkt);
10156 	mutex_enter(ST_MUTEX);
10157 #endif
10158 }
10159 
10160 static char *
10161 st_print_scsi_cmd(char cmd)
10162 {
10163 	char tmp[64];
10164 	char *cpnt;
10165 
10166 	cpnt = scsi_cmd_name(cmd, scsi_cmds, tmp);
10167 	/* tmp goes out of scope on return and caller sees garbage */
10168 	if (cpnt == tmp) {
10169 		cpnt = "Unknown Command";
10170 	}
10171 	return (cpnt);
10172 }
10173 
10174 static void
10175 st_print_cdb(dev_info_t *dip, char *label, uint_t level,
10176     char *title, char *cdb)
10177 {
10178 	int len = scsi_cdb_size[CDB_GROUPID(cdb[0])];
10179 	char buf[256];
10180 	int instance = ddi_get_instance(dip);
10181 	struct scsi_tape *un;
10182 
10183 	un = ddi_get_soft_state(st_state, instance);
10184 
10185 	ST_FUNC(dip, st_print_cdb);
10186 
10187 #ifdef DEBUG
10188 	if ((st_debug & 0x180) == 0x100) {
10189 		scsi_log(dip, label, level, "node %s cmd %s\n",
10190 		    st_dev_name(un->un_dev), st_print_scsi_cmd(*cdb));
10191 		return;
10192 	}
10193 #endif
10194 	(void) sprintf(buf, "%s for cmd(%s)", title, st_print_scsi_cmd(*cdb));
10195 	st_clean_print(dip, label, level, buf, cdb, len);
10196 }
10197 
10198 static void
10199 st_clean_print(dev_info_t *dev, char *label, uint_t level,
10200     char *title, char *data, int len)
10201 {
10202 	int	i;
10203 	int 	c;
10204 	char	*format;
10205 	char	buf[256];
10206 	uchar_t	byte;
10207 
10208 	ST_FUNC(dev, st_clean_print);
10209 
10210 	(void) sprintf(buf, "%s:\n", title);
10211 	scsi_log(dev, label, level, "%s", buf);
10212 	level = CE_CONT;
10213 	for (i = 0; i < len; ) {
10214 		buf[0] = 0;
10215 		for (c = 0; c < 8 && i < len; c++, i++) {
10216 			byte = (uchar_t)data[i];
10217 			if (byte < 0x10)
10218 				format = "0x0%x ";
10219 			else
10220 				format = "0x%x ";
10221 			(void) sprintf(&buf[(int)strlen(buf)], format, byte);
10222 		}
10223 		(void) sprintf(&buf[(int)strlen(buf)], "\n");
10224 
10225 		scsi_log(dev, label, level, "%s\n", buf);
10226 	}
10227 }
10228 
10229 /*
10230  * Conditionally enabled debugging
10231  */
10232 #ifdef	STDEBUG
10233 static void
10234 st_debug_cmds(struct scsi_tape *un, int com, int count, int wait)
10235 {
10236 	char tmpbuf[64];
10237 
10238 	ST_FUNC(ST_DEVINFO, st_debug_cmds);
10239 
10240 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10241 	    "cmd=%s count=0x%x (%d)	 %ssync\n",
10242 	    scsi_cmd_name(com, scsi_cmds, tmpbuf),
10243 	    count, count,
10244 	    wait == ASYNC_CMD ? "a" : "");
10245 }
10246 
10247 /*
10248  * Returns pointer to name of minor node name of device 'dev'.
10249  */
10250 static char *
10251 st_dev_name(dev_t dev)
10252 {
10253 	struct scsi_tape *un;
10254 	const char density[] = { 'l', 'm', 'h', 'c' };
10255 	static char name[4];
10256 	minor_t minor;
10257 	int instance;
10258 	int nprt = 0;
10259 
10260 	minor = getminor(dev);
10261 	instance = ((minor & 0xff80) >> 5) | (minor & 3);
10262 	un = ddi_get_soft_state(st_state, instance);
10263 	if (un) {
10264 		ST_FUNC(ST_DEVINFO, st_dev_name);
10265 	}
10266 
10267 	name[nprt] = density[(minor & MT_DENSITY_MASK) >> 3];
10268 
10269 	if (minor & MT_BSD) {
10270 		name[++nprt] = 'b';
10271 	}
10272 
10273 	if (minor & MT_NOREWIND) {
10274 		name[++nprt] = 'n';
10275 	}
10276 
10277 	/* NULL terminator */
10278 	name[++nprt] = 0;
10279 
10280 	return (name);
10281 }
10282 #endif	/* STDEBUG */
10283 
10284 /*
10285  * Soft error reporting, so far unique to each drive
10286  *
10287  * Currently supported: exabyte and DAT soft error reporting
10288  */
10289 static int
10290 st_report_exabyte_soft_errors(dev_t dev, int flag)
10291 {
10292 	uchar_t *sensep;
10293 	int amt;
10294 	int rval = 0;
10295 	char cdb[CDB_GROUP0], *c = cdb;
10296 	struct uscsi_cmd *com;
10297 
10298 	GET_SOFT_STATE(dev);
10299 
10300 	ST_FUNC(ST_DEVINFO, st_report_exabyte_soft_errors);
10301 
10302 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10303 	    "st_report_exabyte_soft_errors(dev = 0x%lx, flag = %d)\n",
10304 	    dev, flag);
10305 
10306 	ASSERT(mutex_owned(ST_MUTEX));
10307 
10308 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
10309 	sensep = kmem_zalloc(TAPE_SENSE_LENGTH, KM_SLEEP);
10310 
10311 	*c++ = SCMD_REQUEST_SENSE;
10312 	*c++ = 0;
10313 	*c++ = 0;
10314 	*c++ = 0;
10315 	*c++ = TAPE_SENSE_LENGTH;
10316 	/*
10317 	 * set CLRCNT (byte 5, bit 7 which clears the error counts)
10318 	 */
10319 	*c   = (char)0x80;
10320 
10321 	com->uscsi_cdb = cdb;
10322 	com->uscsi_cdblen = CDB_GROUP0;
10323 	com->uscsi_bufaddr = (caddr_t)sensep;
10324 	com->uscsi_buflen = TAPE_SENSE_LENGTH;
10325 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
10326 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
10327 
10328 	rval = st_ioctl_cmd(dev, com, FKIOCTL);
10329 	if (rval || com->uscsi_status) {
10330 		goto done;
10331 	}
10332 
10333 	/*
10334 	 * was there enough data?
10335 	 */
10336 	amt = (int)TAPE_SENSE_LENGTH - com->uscsi_resid;
10337 
10338 	if ((amt >= 19) && un->un_kbytes_xferred) {
10339 		uint_t count, error_rate;
10340 		uint_t rate;
10341 
10342 		if (sensep[21] & CLN) {
10343 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
10344 			    "Periodic head cleaning required");
10345 		}
10346 		if (un->un_kbytes_xferred < (EXABYTE_MIN_TRANSFER/ONE_K)) {
10347 			goto done;
10348 		}
10349 		/*
10350 		 * check if soft error reporting needs to be done.
10351 		 */
10352 		count = sensep[16] << 16 | sensep[17] << 8 | sensep[18];
10353 		count &= 0xffffff;
10354 		error_rate = (count * 100)/un->un_kbytes_xferred;
10355 
10356 #ifdef	STDEBUG
10357 		if (st_soft_error_report_debug) {
10358 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
10359 			    "Exabyte Soft Error Report:\n");
10360 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
10361 			    "read/write error counter: %d\n", count);
10362 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
10363 			    "number of bytes transferred: %dK\n",
10364 			    un->un_kbytes_xferred);
10365 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
10366 			    "error_rate: %d%%\n", error_rate);
10367 
10368 			if (amt >= 22) {
10369 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
10370 				    "unit sense: 0x%b 0x%b 0x%b\n",
10371 				    sensep[19], SENSE_19_BITS,
10372 				    sensep[20], SENSE_20_BITS,
10373 				    sensep[21], SENSE_21_BITS);
10374 			}
10375 			if (amt >= 27) {
10376 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
10377 				    "tracking retry counter: %d\n",
10378 				    sensep[26]);
10379 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
10380 				    "read/write retry counter: %d\n",
10381 				    sensep[27]);
10382 			}
10383 		}
10384 #endif
10385 
10386 		if (flag & FWRITE) {
10387 			rate = EXABYTE_WRITE_ERROR_THRESHOLD;
10388 		} else {
10389 			rate = EXABYTE_READ_ERROR_THRESHOLD;
10390 		}
10391 		if (error_rate >= rate) {
10392 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
10393 			    "Soft error rate (%d%%) during %s was too high",
10394 			    error_rate,
10395 			    ((flag & FWRITE) ? wrg_str : rdg_str));
10396 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
10397 			    "Please, replace tape cartridge\n");
10398 		}
10399 	}
10400 
10401 done:
10402 	kmem_free(com, sizeof (*com));
10403 	kmem_free(sensep, TAPE_SENSE_LENGTH);
10404 
10405 	if (rval != 0) {
10406 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
10407 		    "exabyte soft error reporting failed\n");
10408 	}
10409 	return (rval);
10410 }
10411 
10412 /*
10413  * this is very specific to Archive 4mm dat
10414  */
10415 #define	ONE_GIG	(ONE_K * ONE_K * ONE_K)
10416 
10417 static int
10418 st_report_dat_soft_errors(dev_t dev, int flag)
10419 {
10420 	uchar_t *sensep;
10421 	int amt, i;
10422 	int rval = 0;
10423 	char cdb[CDB_GROUP1], *c = cdb;
10424 	struct uscsi_cmd *com;
10425 
10426 	GET_SOFT_STATE(dev);
10427 
10428 	ST_FUNC(ST_DEVINFO, st_report_dat_soft_errors);
10429 
10430 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10431 	    "st_report_dat_soft_errors(dev = 0x%lx, flag = %d)\n", dev, flag);
10432 
10433 	ASSERT(mutex_owned(ST_MUTEX));
10434 
10435 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
10436 	sensep = kmem_zalloc(LOG_SENSE_LENGTH, KM_SLEEP);
10437 
10438 	*c++ = SCMD_LOG_SENSE_G1;
10439 	*c++ = 0;
10440 	*c++ = (flag & FWRITE) ? 0x42 : 0x43;
10441 	*c++ = 0;
10442 	*c++ = 0;
10443 	*c++ = 0;
10444 	*c++ = 2;
10445 	*c++ = 0;
10446 	*c++ = (char)LOG_SENSE_LENGTH;
10447 	*c   = 0;
10448 	com->uscsi_cdb    = cdb;
10449 	com->uscsi_cdblen  = CDB_GROUP1;
10450 	com->uscsi_bufaddr = (caddr_t)sensep;
10451 	com->uscsi_buflen  = LOG_SENSE_LENGTH;
10452 	com->uscsi_flags   =
10453 	    USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
10454 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
10455 	rval = st_ioctl_cmd(dev, com, FKIOCTL);
10456 	if (rval) {
10457 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
10458 		    "DAT soft error reporting failed\n");
10459 	}
10460 	if (rval || com->uscsi_status) {
10461 		goto done;
10462 	}
10463 
10464 	/*
10465 	 * was there enough data?
10466 	 */
10467 	amt = (int)LOG_SENSE_LENGTH - com->uscsi_resid;
10468 
10469 	if ((amt >= MIN_LOG_SENSE_LENGTH) && un->un_kbytes_xferred) {
10470 		int total, retries, param_code;
10471 
10472 		total = -1;
10473 		retries = -1;
10474 		amt = sensep[3] + 4;
10475 
10476 
10477 #ifdef STDEBUG
10478 		if (st_soft_error_report_debug) {
10479 			(void) printf("logsense:");
10480 			for (i = 0; i < MIN_LOG_SENSE_LENGTH; i++) {
10481 				if (i % 16 == 0) {
10482 					(void) printf("\t\n");
10483 				}
10484 				(void) printf(" %x", sensep[i]);
10485 			}
10486 			(void) printf("\n");
10487 		}
10488 #endif
10489 
10490 		/*
10491 		 * parse the param_codes
10492 		 */
10493 		if (sensep[0] == 2 || sensep[0] == 3) {
10494 			for (i = 4; i < amt; i++) {
10495 				param_code = (sensep[i++] << 8);
10496 				param_code += sensep[i++];
10497 				i++; /* skip control byte */
10498 				if (param_code == 5) {
10499 					if (sensep[i++] == 4) {
10500 						total = (sensep[i++] << 24);
10501 						total += (sensep[i++] << 16);
10502 						total += (sensep[i++] << 8);
10503 						total += sensep[i];
10504 					}
10505 				} else if (param_code == 0x8007) {
10506 					if (sensep[i++] == 2) {
10507 						retries = sensep[i++] << 8;
10508 						retries += sensep[i];
10509 					}
10510 				} else {
10511 					i += sensep[i];
10512 				}
10513 			}
10514 		}
10515 
10516 		/*
10517 		 * if the log sense returned valid numbers then determine
10518 		 * the read and write error thresholds based on the amount of
10519 		 * data transferred
10520 		 */
10521 
10522 		if (total > 0 && retries > 0) {
10523 			short normal_retries = 0;
10524 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10525 			    "total xferred (%s) =%x, retries=%x\n",
10526 			    ((flag & FWRITE) ? wrg_str : rdg_str),
10527 			    total, retries);
10528 
10529 			if (flag & FWRITE) {
10530 				if (total <=
10531 				    WRITE_SOFT_ERROR_WARNING_THRESHOLD) {
10532 					normal_retries =
10533 					    DAT_SMALL_WRITE_ERROR_THRESHOLD;
10534 				} else {
10535 					normal_retries =
10536 					    DAT_LARGE_WRITE_ERROR_THRESHOLD;
10537 				}
10538 			} else {
10539 				if (total <=
10540 				    READ_SOFT_ERROR_WARNING_THRESHOLD) {
10541 					normal_retries =
10542 					    DAT_SMALL_READ_ERROR_THRESHOLD;
10543 				} else {
10544 					normal_retries =
10545 					    DAT_LARGE_READ_ERROR_THRESHOLD;
10546 				}
10547 			}
10548 
10549 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10550 			"normal retries=%d\n", normal_retries);
10551 
10552 			if (retries >= normal_retries) {
10553 				scsi_log(ST_DEVINFO, st_label, CE_WARN,
10554 				    "Soft error rate (retries = %d) during "
10555 				    "%s was too high",  retries,
10556 				    ((flag & FWRITE) ? wrg_str : rdg_str));
10557 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
10558 				    "Periodic head cleaning required "
10559 				    "and/or replace tape cartridge\n");
10560 			}
10561 
10562 		} else if (total == -1 || retries == -1) {
10563 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
10564 			    "log sense parameter code does not make sense\n");
10565 		}
10566 	}
10567 
10568 	/*
10569 	 * reset all values
10570 	 */
10571 	c = cdb;
10572 	*c++ = SCMD_LOG_SELECT_G1;
10573 	*c++ = 2;	/* this resets all values */
10574 	*c++ = (char)0xc0;
10575 	*c++ = 0;
10576 	*c++ = 0;
10577 	*c++ = 0;
10578 	*c++ = 0;
10579 	*c++ = 0;
10580 	*c++ = 0;
10581 	*c   = 0;
10582 	com->uscsi_bufaddr = NULL;
10583 	com->uscsi_buflen  = 0;
10584 	com->uscsi_flags   = USCSI_DIAGNOSE | USCSI_SILENT;
10585 	rval = st_ioctl_cmd(dev, com, FKIOCTL);
10586 	if (rval) {
10587 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
10588 		    "DAT soft error reset failed\n");
10589 	}
10590 done:
10591 	kmem_free(com, sizeof (*com));
10592 	kmem_free(sensep, LOG_SENSE_LENGTH);
10593 	return (rval);
10594 }
10595 
10596 static int
10597 st_report_soft_errors(dev_t dev, int flag)
10598 {
10599 	GET_SOFT_STATE(dev);
10600 
10601 	ST_FUNC(ST_DEVINFO, st_report_soft_errors);
10602 
10603 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10604 	    "st_report_soft_errors(dev = 0x%lx, flag = %d)\n", dev, flag);
10605 
10606 	ASSERT(mutex_owned(ST_MUTEX));
10607 
10608 	switch (un->un_dp->type) {
10609 	case ST_TYPE_EXB8500:
10610 	case ST_TYPE_EXABYTE:
10611 		return (st_report_exabyte_soft_errors(dev, flag));
10612 		/*NOTREACHED*/
10613 	case ST_TYPE_PYTHON:
10614 		return (st_report_dat_soft_errors(dev, flag));
10615 		/*NOTREACHED*/
10616 	default:
10617 		un->un_dp->options &= ~ST_SOFT_ERROR_REPORTING;
10618 		return (-1);
10619 	}
10620 }
10621 
10622 /*
10623  * persistent error routines
10624  */
10625 
10626 /*
10627  * enable persistent errors, and set the throttle appropriately, checking
10628  * for flush-on-errors capability
10629  */
10630 static void
10631 st_turn_pe_on(struct scsi_tape *un)
10632 {
10633 	ST_FUNC(ST_DEVINFO, st_turn_pe_on);
10634 
10635 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_on\n");
10636 	ASSERT(mutex_owned(ST_MUTEX));
10637 
10638 	un->un_persistence = 1;
10639 
10640 	/*
10641 	 * only use flush-on-errors if auto-request-sense and untagged-qing are
10642 	 * enabled.  This will simplify the error handling for request senses
10643 	 */
10644 
10645 	if (un->un_arq_enabled && un->un_untagged_qing) {
10646 		uchar_t f_o_e;
10647 
10648 		mutex_exit(ST_MUTEX);
10649 		f_o_e = (scsi_ifsetcap(ROUTE, "flush-on-errors", 1, 1) == 1) ?
10650 		    1 : 0;
10651 		mutex_enter(ST_MUTEX);
10652 
10653 		un->un_flush_on_errors = f_o_e;
10654 	} else {
10655 		un->un_flush_on_errors = 0;
10656 	}
10657 
10658 	if (un->un_flush_on_errors)
10659 		un->un_max_throttle = (uchar_t)st_max_throttle;
10660 	else
10661 		un->un_max_throttle = 1;
10662 
10663 	if (un->un_dp->options & ST_RETRY_ON_RECOVERED_DEFERRED_ERROR)
10664 		un->un_max_throttle = 1;
10665 
10666 	/* this will send a marker pkt */
10667 	CLEAR_PE(un);
10668 }
10669 
10670 /*
10671  * This turns persistent errors permanently off
10672  */
10673 static void
10674 st_turn_pe_off(struct scsi_tape *un)
10675 {
10676 	ST_FUNC(ST_DEVINFO, st_turn_pe_off);
10677 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_off\n");
10678 	ASSERT(mutex_owned(ST_MUTEX));
10679 
10680 	/* turn it off for good */
10681 	un->un_persistence = 0;
10682 
10683 	/* this will send a marker pkt */
10684 	CLEAR_PE(un);
10685 
10686 	/* turn off flush on error capability, if enabled */
10687 	if (un->un_flush_on_errors) {
10688 		mutex_exit(ST_MUTEX);
10689 		(void) scsi_ifsetcap(ROUTE, "flush-on-errors", 0, 1);
10690 		mutex_enter(ST_MUTEX);
10691 	}
10692 
10693 
10694 	un->un_flush_on_errors = 0;
10695 }
10696 
10697 /*
10698  * This clear persistent errors, allowing more commands through, and also
10699  * sending a marker packet.
10700  */
10701 static void
10702 st_clear_pe(struct scsi_tape *un)
10703 {
10704 	ST_FUNC(ST_DEVINFO, st_clear_pe);
10705 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_clear\n");
10706 	ASSERT(mutex_owned(ST_MUTEX));
10707 
10708 	un->un_persist_errors = 0;
10709 	un->un_throttle = un->un_last_throttle = 1;
10710 	un->un_errno = 0;
10711 	st_hba_unflush(un);
10712 }
10713 
10714 /*
10715  * This will flag persistent errors, shutting everything down, if the
10716  * application had enabled persistent errors via MTIOCPERSISTENT
10717  */
10718 static void
10719 st_set_pe_flag(struct scsi_tape *un)
10720 {
10721 	ST_FUNC(ST_DEVINFO, st_set_pe_flag);
10722 	ASSERT(mutex_owned(ST_MUTEX));
10723 
10724 	if (un->un_persistence) {
10725 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_flag\n");
10726 		un->un_persist_errors = 1;
10727 		un->un_throttle = un->un_last_throttle = 0;
10728 	}
10729 }
10730 
10731 /*
10732  * List of commands that are allowed to be done while another host holds
10733  * the reservation.
10734  */
10735 struct {
10736 	uchar_t cmd;
10737 	uchar_t byte;	/* byte to look for data */
10738 	uint32_t mask;	/* bits that matter in the above data */
10739 } rcmds[] = {
10740 	{ SCMD_TEST_UNIT_READY, 0, 0 }, /* may fail on older drives */
10741 	{ SCMD_REQUEST_SENSE, 0, 0 },
10742 	{ SCMD_READ_BLKLIM, 0, 0 },
10743 	{ SCMD_INQUIRY, 0, 0 },
10744 	{ SCMD_RESERVE, 0, 0 },
10745 	{ SCMD_RELEASE, 0, 0 },
10746 	{ SCMD_DOORLOCK, 4, 3 },	/* allow (unlock) media access only */
10747 	{ SCMD_REPORT_DENSITIES, 0, 0 },
10748 	{ SCMD_LOG_SENSE_G1, 0, 0 },
10749 	{ SCMD_PERSISTENT_RESERVE_IN, 0, 0 },
10750 	{ SCMD_PERSISTENT_RESERVE_OUT, 0, 0 },
10751 	{ SCMD_REPORT_LUNS, 0, 0 }
10752 };
10753 
10754 static int
10755 st_do_reserve(struct scsi_tape *un)
10756 {
10757 	int rval;
10758 
10759 	ST_FUNC(ST_DEVINFO, st_do_reserve);
10760 
10761 	/*
10762 	 * Issue a Throw-Away reserve command to clear the
10763 	 * check condition.
10764 	 * If the current behaviour of reserve/release is to
10765 	 * hold reservation across opens , and if a Bus reset
10766 	 * has been issued between opens then this command
10767 	 * would set the ST_LOST_RESERVE flags in rsvd_status.
10768 	 * In this case return an EACCES so that user knows that
10769 	 * reservation has been lost in between opens.
10770 	 * If this error is not returned and we continue with
10771 	 * successful open , then user may think position of the
10772 	 * tape is still the same but inreality we would rewind the
10773 	 * tape and continue from BOT.
10774 	 */
10775 	rval = st_reserve_release(un, ST_RESERVE);
10776 	if (rval) {
10777 		if ((un->un_rsvd_status & ST_LOST_RESERVE_BETWEEN_OPENS) ==
10778 		    ST_LOST_RESERVE_BETWEEN_OPENS) {
10779 			un->un_rsvd_status &= ~(ST_LOST_RESERVE | ST_RESERVE);
10780 			un->un_errno = EACCES;
10781 			return (EACCES);
10782 		}
10783 		rval = st_reserve_release(un, ST_RESERVE);
10784 	}
10785 	if (rval == 0) {
10786 		un->un_rsvd_status |= ST_INIT_RESERVE;
10787 	}
10788 
10789 	return (rval);
10790 }
10791 
10792 static int
10793 st_check_cdb_for_need_to_reserve(struct scsi_tape *un, caddr_t cdb)
10794 {
10795 	int i;
10796 	int rval = 0;
10797 
10798 	ST_FUNC(ST_DEVINFO, st_check_cdb_for_need_to_reserve);
10799 
10800 	/*
10801 	 * If already reserved no need to do it again.
10802 	 * Also if Reserve and Release are disabled Just return.
10803 	 */
10804 	if ((un->un_rsvd_status & (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) ||
10805 	    (un->un_dp->options & ST_NO_RESERVE_RELEASE)) {
10806 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
10807 		    "st_check_cdb_for_need_to_reserve() reserve unneeded %s",
10808 		    st_print_scsi_cmd((uchar_t)cdb[0]));
10809 		return (0);
10810 	}
10811 
10812 	/* See if command is on the list */
10813 	for (i = 0; i < ST_NUM_MEMBERS(rcmds); i++) {
10814 		if ((uchar_t)cdb[0] == rcmds[i].cmd) {
10815 			/*
10816 			 * cmd is on list.
10817 			 * if byte is zero always allowed.
10818 			 */
10819 			if (rcmds[i].byte == 0) {
10820 				return (rval);
10821 			}
10822 			if (((cdb[rcmds[i].byte]) & (rcmds[i].mask)) == 0) {
10823 				return (rval);
10824 			}
10825 			break;
10826 		}
10827 	}
10828 
10829 	ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
10830 	    "Command %s requires reservation", st_print_scsi_cmd(cdb[0]));
10831 
10832 	rval = st_do_reserve(un);
10833 
10834 	return (rval);
10835 }
10836 
10837 static int
10838 st_check_cmd_for_need_to_reserve(struct scsi_tape *un, uchar_t cmd, int cnt)
10839 {
10840 	int i;
10841 	int rval = 0;
10842 
10843 	ST_FUNC(ST_DEVINFO, st_check_cmd_for_need_to_reserve);
10844 
10845 	if ((un->un_rsvd_status & (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) ||
10846 	    (un->un_dp->options & ST_NO_RESERVE_RELEASE)) {
10847 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
10848 		    "st_check_cmd_for_need_to_reserve() reserve unneeded %s",
10849 		    st_print_scsi_cmd(cmd));
10850 		return (0);
10851 	}
10852 
10853 	/* See if command is on the list */
10854 	for (i = 0; i < ST_NUM_MEMBERS(rcmds); i++) {
10855 		if (cmd == rcmds[i].cmd) {
10856 			/*
10857 			 * cmd is on list.
10858 			 * if byte is zero always allowed.
10859 			 */
10860 			if (rcmds[i].byte == 0) {
10861 				return (rval);
10862 			}
10863 			if (((rcmds[i].mask) & cnt) == 0) {
10864 				return (rval);
10865 			}
10866 			break;
10867 		}
10868 	}
10869 
10870 	ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
10871 	    "Cmd %s requires reservation", st_print_scsi_cmd(cmd));
10872 
10873 	rval = st_do_reserve(un);
10874 
10875 	return (rval);
10876 }
10877 
10878 static int
10879 st_reserve_release(struct scsi_tape *un, int cmd)
10880 {
10881 	struct uscsi_cmd	uscsi_cmd;
10882 	struct uscsi_cmd	*com = &uscsi_cmd;
10883 	int			rval;
10884 	char			cdb[CDB_GROUP0];
10885 
10886 
10887 
10888 	ST_FUNC(ST_DEVINFO, st_reserve_release);
10889 
10890 	ASSERT(mutex_owned(ST_MUTEX));
10891 
10892 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10893 	    "st_reserve_release: %s \n",
10894 	    (cmd == ST_RELEASE)?  "Releasing":"Reserving");
10895 
10896 	bzero(cdb, CDB_GROUP0);
10897 	if (cmd == ST_RELEASE) {
10898 		cdb[0] = SCMD_RELEASE;
10899 	} else {
10900 		cdb[0] = SCMD_RESERVE;
10901 	}
10902 	bzero(com, sizeof (struct uscsi_cmd));
10903 	com->uscsi_flags = USCSI_WRITE;
10904 	com->uscsi_cdb = cdb;
10905 	com->uscsi_cdblen = CDB_GROUP0;
10906 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
10907 
10908 	rval = st_ioctl_cmd(un->un_dev, com, FKIOCTL);
10909 
10910 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10911 	    "st_reserve_release: rval(1)=%d\n", rval);
10912 
10913 	if (rval) {
10914 		if (com->uscsi_status == STATUS_RESERVATION_CONFLICT) {
10915 			rval = EACCES;
10916 		}
10917 		/*
10918 		 * dynamically turn off reserve/release support
10919 		 * in case of drives which do not support
10920 		 * reserve/release command(ATAPI drives).
10921 		 */
10922 		if (un->un_status == KEY_ILLEGAL_REQUEST) {
10923 			if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
10924 				un->un_dp->options |= ST_NO_RESERVE_RELEASE;
10925 				ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10926 				    "Tape unit does not support "
10927 				    "reserve/release \n");
10928 			}
10929 			rval = 0;
10930 		}
10931 	}
10932 	return (rval);
10933 }
10934 
10935 static int
10936 st_take_ownership(dev_t dev)
10937 {
10938 	int rval;
10939 
10940 	GET_SOFT_STATE(dev);
10941 
10942 	ST_FUNC(ST_DEVINFO, st_take_ownership);
10943 
10944 	ASSERT(mutex_owned(ST_MUTEX));
10945 
10946 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10947 	    "st_take_ownership: Entering ...\n");
10948 
10949 
10950 	rval = st_reserve_release(un, ST_RESERVE);
10951 	/*
10952 	 * XXX -> Should reset be done only if we get EACCES.
10953 	 * .
10954 	 */
10955 	if (rval) {
10956 		mutex_exit(ST_MUTEX);
10957 		if (scsi_reset(ROUTE, RESET_TARGET) == 0) {
10958 			if (scsi_reset(ROUTE, RESET_ALL) == 0) {
10959 				mutex_enter(ST_MUTEX);
10960 				return (EIO);
10961 			}
10962 		}
10963 		mutex_enter(ST_MUTEX);
10964 		un->un_rsvd_status &=
10965 		    ~(ST_LOST_RESERVE | ST_RESERVATION_CONFLICT);
10966 
10967 		mutex_exit(ST_MUTEX);
10968 		delay(drv_usectohz(ST_RESERVATION_DELAY));
10969 		mutex_enter(ST_MUTEX);
10970 		/*
10971 		 * remove the check condition.
10972 		 */
10973 		(void) st_reserve_release(un, ST_RESERVE);
10974 		if ((rval = st_reserve_release(un, ST_RESERVE)) != 0) {
10975 			if ((st_reserve_release(un, ST_RESERVE)) != 0) {
10976 				rval = (un->un_rsvd_status &
10977 				    ST_RESERVATION_CONFLICT) ? EACCES : EIO;
10978 				return (rval);
10979 			}
10980 		}
10981 		/*
10982 		 * Set tape state to ST_STATE_OFFLINE , in case if
10983 		 * the user wants to continue and start using
10984 		 * the tape.
10985 		 */
10986 		un->un_state = ST_STATE_OFFLINE;
10987 		un->un_rsvd_status |= ST_INIT_RESERVE;
10988 	}
10989 	return (rval);
10990 }
10991 
10992 static int
10993 st_create_errstats(struct scsi_tape *un, int instance)
10994 {
10995 	char	kstatname[KSTAT_STRLEN];
10996 
10997 	ST_FUNC(ST_DEVINFO, st_create_errstats);
10998 
10999 	/*
11000 	 * Create device error kstats
11001 	 */
11002 
11003 	if (un->un_errstats == (kstat_t *)0) {
11004 		(void) sprintf(kstatname, "st%d,err", instance);
11005 		un->un_errstats = kstat_create("sterr", instance, kstatname,
11006 		    "device_error", KSTAT_TYPE_NAMED,
11007 		    sizeof (struct st_errstats) / sizeof (kstat_named_t),
11008 		    KSTAT_FLAG_PERSISTENT);
11009 
11010 		if (un->un_errstats) {
11011 			struct st_errstats	*stp;
11012 
11013 			stp = (struct st_errstats *)un->un_errstats->ks_data;
11014 			kstat_named_init(&stp->st_softerrs, "Soft Errors",
11015 			    KSTAT_DATA_ULONG);
11016 			kstat_named_init(&stp->st_harderrs, "Hard Errors",
11017 			    KSTAT_DATA_ULONG);
11018 			kstat_named_init(&stp->st_transerrs, "Transport Errors",
11019 			    KSTAT_DATA_ULONG);
11020 			kstat_named_init(&stp->st_vid, "Vendor",
11021 			    KSTAT_DATA_CHAR);
11022 			kstat_named_init(&stp->st_pid, "Product",
11023 			    KSTAT_DATA_CHAR);
11024 			kstat_named_init(&stp->st_revision, "Revision",
11025 			    KSTAT_DATA_CHAR);
11026 			kstat_named_init(&stp->st_serial, "Serial No",
11027 			    KSTAT_DATA_CHAR);
11028 			un->un_errstats->ks_private = un;
11029 			un->un_errstats->ks_update = nulldev;
11030 			kstat_install(un->un_errstats);
11031 			/*
11032 			 * Fill in the static data
11033 			 */
11034 			(void) strncpy(&stp->st_vid.value.c[0],
11035 			    ST_INQUIRY->inq_vid, 8);
11036 			/*
11037 			 * XXX:  Emulex MT-02 (and emulators) predates
11038 			 *	 SCSI-1 and has no vid & pid inquiry data.
11039 			 */
11040 			if (ST_INQUIRY->inq_len != 0) {
11041 				(void) strncpy(&stp->st_pid.value.c[0],
11042 				    ST_INQUIRY->inq_pid, 16);
11043 				(void) strncpy(&stp->st_revision.value.c[0],
11044 				    ST_INQUIRY->inq_revision, 4);
11045 				(void) strncpy(&stp->st_serial.value.c[0],
11046 				    ST_INQUIRY->inq_serial, 12);
11047 			}
11048 		}
11049 	}
11050 	return (0);
11051 }
11052 
11053 static int
11054 st_validate_tapemarks(struct scsi_tape *un, tapepos_t *pos)
11055 {
11056 	dev_t dev;
11057 	int rval;
11058 
11059 	ST_FUNC(ST_DEVINFO, st_validate_tapemarks);
11060 
11061 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
11062 	ASSERT(mutex_owned(ST_MUTEX));
11063 
11064 	/* Can't restore an invalid position */
11065 	if (pos->pmode == invalid) {
11066 		return (4);
11067 	}
11068 
11069 	/*
11070 	 * Assumtions:
11071 	 *	If a position was read and is in logical position mode.
11072 	 *	If a drive supports read position it supports locate.
11073 	 *	If the read position type is not NO_POS. even though
11074 	 *	   a read position make not have been attemped yet.
11075 	 *
11076 	 *	The drive can locate to the position.
11077 	 */
11078 	if (pos->pmode == logical || un->un_read_pos_type != NO_POS) {
11079 		/*
11080 		 * If position mode is logical or legacy mode try
11081 		 * to locate there as it is faster.
11082 		 * If it fails try the old way.
11083 		 */
11084 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
11085 		    "Restoring tape position to lgclblkbo=0x%"PRIx64"....",
11086 		    pos->lgclblkno);
11087 
11088 		if (st_logical_block_locate(un, pos->lgclblkno, pos->partition)
11089 		    == 0) {
11090 			/* Assume we are there copy rest of position back */
11091 			if (un->un_pos.lgclblkno == pos->lgclblkno) {
11092 				COPY_POS(&un->un_pos, pos);
11093 			}
11094 			return (0);
11095 		}
11096 
11097 		/*
11098 		 * If logical block locate failed to restore a logical
11099 		 * position, can't recover.
11100 		 */
11101 		if (pos->pmode == logical) {
11102 			return (-1);
11103 		}
11104 	}
11105 
11106 	dev = un->un_dev;
11107 
11108 	scsi_log(ST_DEVINFO, st_label, CE_NOTE,
11109 	    "Restoring tape position at fileno=%x, blkno=%x....",
11110 	    pos->fileno, pos->blkno);
11111 
11112 	/*
11113 	 * Rewind ? Oh yeah, Fidelity has got the STK F/W changed
11114 	 * so as not to rewind tape on RESETS: Gee, Has life ever
11115 	 * been simple in tape land ?
11116 	 */
11117 	rval = st_cmd(dev, SCMD_REWIND, 0, SYNC_CMD);
11118 	if (rval) {
11119 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
11120 		"Failed to restore the last file and block position: In"
11121 		" this state, Tape will be loaded at BOT during next open");
11122 		un->un_pos.pmode = invalid;
11123 		return (rval);
11124 	}
11125 
11126 	/* If the position was as the result of back space file */
11127 	if (pos->blkno > (INF / 2)) {
11128 		/* Go one extra file forward */
11129 		pos->fileno++;
11130 		/* Figure how many blocks to back into the previous file */
11131 		pos->blkno = -(INF - pos->blkno);
11132 	}
11133 
11134 	/* Go to requested fileno */
11135 	if (pos->fileno) {
11136 		rval = st_cmd(dev, SCMD_SPACE, Fmk(pos->fileno), SYNC_CMD);
11137 		if (rval) {
11138 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
11139 			    "Failed to restore the last file position: In this "
11140 			    " state, Tape will be loaded at BOT during next"
11141 			    " open %d", __LINE__);
11142 			un->un_pos.pmode = invalid;
11143 			pos->pmode = invalid;
11144 			return (rval);
11145 		}
11146 	}
11147 
11148 	/*
11149 	 * If backing into a file we already did an extra file forward.
11150 	 * Now we have to back over the filemark to get to the end of
11151 	 * the previous file. The blkno has been ajusted to a negative
11152 	 * value so we will get to the expected location.
11153 	 */
11154 	if (pos->blkno) {
11155 		rval = st_cmd(dev, SCMD_SPACE, Fmk(-1), SYNC_CMD);
11156 		if (rval) {
11157 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
11158 			    "Failed to restore the last file position: In this "
11159 			    " state, Tape will be loaded at BOT during next"
11160 			    " open %d", __LINE__);
11161 			un->un_pos.pmode = invalid;
11162 			pos->pmode = invalid;
11163 			return (rval);
11164 		}
11165 	}
11166 
11167 	/*
11168 	 * The position mode, block and fileno should be correct,
11169 	 * This updates eof and logical position information.
11170 	 */
11171 	un->un_pos.eof = pos->eof;
11172 	un->un_pos.lgclblkno = pos->lgclblkno;
11173 
11174 	return (0);
11175 }
11176 
11177 /*
11178  * check sense key, ASC, ASCQ in order to determine if the tape needs
11179  * to be ejected
11180  */
11181 
11182 static int
11183 st_check_asc_ascq(struct scsi_tape *un)
11184 {
11185 	struct scsi_extended_sense *sensep = ST_RQSENSE;
11186 	struct tape_failure_code   *code;
11187 
11188 	ST_FUNC(ST_DEVINFO, st_check_asc_ascq);
11189 
11190 	for (code = st_tape_failure_code; code->key != 0xff; code++) {
11191 		if ((code->key  == sensep->es_key) &&
11192 		    (code->add_code  == sensep->es_add_code) &&
11193 		    (code->qual_code == sensep->es_qual_code))
11194 			return (1);
11195 	}
11196 	return (0);
11197 }
11198 
11199 /*
11200  * st_logpage_supported() sends a Log Sense command with
11201  * page code = 0 = Supported Log Pages Page to the device,
11202  * to see whether the page 'page' is supported.
11203  * Return values are:
11204  * -1 if the Log Sense command fails
11205  * 0 if page is not supported
11206  * 1 if page is supported
11207  */
11208 
11209 static int
11210 st_logpage_supported(dev_t dev, uchar_t page)
11211 {
11212 	uchar_t *sp, *sensep;
11213 	unsigned length;
11214 	struct uscsi_cmd *com;
11215 	int rval;
11216 	char cdb[CDB_GROUP1] = {
11217 		SCMD_LOG_SENSE_G1,
11218 		0,
11219 		SUPPORTED_LOG_PAGES_PAGE,
11220 		0,
11221 		0,
11222 		0,
11223 		0,
11224 		0,
11225 		(char)LOG_SENSE_LENGTH,
11226 		0
11227 	};
11228 
11229 	GET_SOFT_STATE(dev);
11230 
11231 	ST_FUNC(ST_DEVINFO, st_logpage_supported);
11232 
11233 	ASSERT(mutex_owned(ST_MUTEX));
11234 
11235 	com = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
11236 	sensep = kmem_zalloc(LOG_SENSE_LENGTH, KM_SLEEP);
11237 
11238 	com->uscsi_cdb = cdb;
11239 	com->uscsi_cdblen = CDB_GROUP1;
11240 	com->uscsi_bufaddr = (caddr_t)sensep;
11241 	com->uscsi_buflen = LOG_SENSE_LENGTH;
11242 	com->uscsi_flags =
11243 	    USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
11244 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
11245 	rval = st_ioctl_cmd(dev, com, FKIOCTL);
11246 	if (rval || com->uscsi_status) {
11247 		/* uscsi-command failed */
11248 		rval = -1;
11249 	} else {
11250 
11251 		sp = sensep + 3;
11252 
11253 		for (length = *sp++; length > 0; length--, sp++) {
11254 
11255 			if (*sp == page) {
11256 				rval = 1;
11257 				break;
11258 			}
11259 		}
11260 	}
11261 	kmem_free(com, sizeof (struct uscsi_cmd));
11262 	kmem_free(sensep, LOG_SENSE_LENGTH);
11263 	return (rval);
11264 }
11265 
11266 
11267 /*
11268  * st_check_clean_bit() gets the status of the tape's cleaning bit.
11269  *
11270  * If the device does support the TapeAlert log page, then the cleaning bit
11271  * information will be read from this page. Otherwise we will see if one of
11272  * ST_CLN_TYPE_1, ST_CLN_TYPE_2 or ST_CLN_TYPE_3 is set in the properties of
11273  * the device, which means, that we can get the cleaning bit information via
11274  * a RequestSense command.
11275  * If both methods of getting cleaning bit information are not supported
11276  * st_check_clean_bit() will return with 0. Otherwise st_check_clean_bit()
11277  * returns with
11278  * - MTF_TAPE_CLN_SUPPORTED if cleaning bit is not set or
11279  * - MTF_TAPE_CLN_SUPPORTED | MTF_TAPE_HEAD_DIRTY if cleaning bit is set.
11280  * If the call to st_ioctl_cmd() to do the Log Sense or the Request Sense
11281  * command fails, or if the amount of Request Sense data is not enough, then
11282  *  st_check_clean_bit() returns with -1.
11283  */
11284 
11285 static int
11286 st_check_clean_bit(dev_t dev)
11287 {
11288 	int rval = 0;
11289 
11290 	GET_SOFT_STATE(dev);
11291 
11292 	ST_FUNC(ST_DEVINFO, st_check_clean_bit);
11293 
11294 	ASSERT(mutex_owned(ST_MUTEX));
11295 
11296 	if (un->un_HeadClean & TAPE_ALERT_NOT_SUPPORTED) {
11297 		return (rval);
11298 	}
11299 
11300 	if (un->un_HeadClean == TAPE_ALERT_SUPPORT_UNKNOWN) {
11301 
11302 		rval = st_logpage_supported(dev, TAPE_SEQUENTIAL_PAGE);
11303 		if (rval == 1) {
11304 
11305 			un->un_HeadClean |= TAPE_SEQUENTIAL_SUPPORTED;
11306 		}
11307 
11308 		rval = st_logpage_supported(dev, TAPE_ALERT_PAGE);
11309 		if (rval == 1) {
11310 
11311 			un->un_HeadClean |= TAPE_ALERT_SUPPORTED;
11312 		}
11313 
11314 		if (un->un_HeadClean == TAPE_ALERT_SUPPORT_UNKNOWN) {
11315 
11316 			un->un_HeadClean = TAPE_ALERT_NOT_SUPPORTED;
11317 		}
11318 	}
11319 
11320 	rval = 0;
11321 
11322 	if (un->un_HeadClean & TAPE_SEQUENTIAL_SUPPORTED) {
11323 
11324 		rval = st_check_sequential_clean_bit(dev);
11325 	}
11326 
11327 	if ((rval <= 0) && (un->un_HeadClean & TAPE_ALERT_SUPPORTED)) {
11328 
11329 		rval = st_check_alert_flags(dev);
11330 	}
11331 
11332 	if ((rval <= 0) && (un->un_dp->options & ST_CLN_MASK)) {
11333 
11334 		rval = st_check_sense_clean_bit(dev);
11335 	}
11336 
11337 	if (rval < 0) {
11338 		return (rval);
11339 	}
11340 
11341 	/*
11342 	 * If found a supported means to check need to clean.
11343 	 */
11344 	if (rval & MTF_TAPE_CLN_SUPPORTED) {
11345 
11346 		/*
11347 		 * head needs to be cleaned.
11348 		 */
11349 		if (rval & MTF_TAPE_HEAD_DIRTY) {
11350 
11351 			/*
11352 			 * Print log message only first time
11353 			 * found needing cleaned.
11354 			 */
11355 			if ((un->un_HeadClean & TAPE_PREVIOUSLY_DIRTY) == 0) {
11356 
11357 				scsi_log(ST_DEVINFO, st_label, CE_WARN,
11358 				    "Periodic head cleaning required");
11359 
11360 				un->un_HeadClean |= TAPE_PREVIOUSLY_DIRTY;
11361 			}
11362 
11363 		} else {
11364 
11365 			un->un_HeadClean &= ~TAPE_PREVIOUSLY_DIRTY;
11366 		}
11367 	}
11368 
11369 	return (rval);
11370 }
11371 
11372 
11373 static int
11374 st_check_sequential_clean_bit(dev_t dev)
11375 {
11376 	int rval;
11377 	int ix;
11378 	ushort_t parameter;
11379 	struct uscsi_cmd *cmd;
11380 	struct log_sequential_page *sp;
11381 	struct log_sequential_page_parameter *prm;
11382 	char cdb[CDB_GROUP1] = {
11383 		SCMD_LOG_SENSE_G1,
11384 		0,
11385 		TAPE_SEQUENTIAL_PAGE | CURRENT_CUMULATIVE_VALUES,
11386 		0,
11387 		0,
11388 		0,
11389 		0,
11390 		(char)(sizeof (struct log_sequential_page) >> 8),
11391 		(char)(sizeof (struct log_sequential_page)),
11392 		0
11393 	};
11394 
11395 	GET_SOFT_STATE(dev);
11396 
11397 	ST_FUNC(ST_DEVINFO, st_check_sequential_clean_bit);
11398 
11399 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
11400 	sp  = kmem_zalloc(sizeof (struct log_sequential_page), KM_SLEEP);
11401 
11402 	cmd->uscsi_flags   =
11403 	    USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
11404 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
11405 	cmd->uscsi_cdb	   = cdb;
11406 	cmd->uscsi_cdblen  = CDB_GROUP1;
11407 	cmd->uscsi_bufaddr = (caddr_t)sp;
11408 	cmd->uscsi_buflen  = sizeof (struct log_sequential_page);
11409 
11410 	rval = st_ioctl_cmd(dev, cmd, FKIOCTL);
11411 
11412 	if (rval || cmd->uscsi_status || cmd->uscsi_resid) {
11413 
11414 		rval = -1;
11415 
11416 	} else if (sp->log_page.code != TAPE_SEQUENTIAL_PAGE) {
11417 
11418 		rval = -1;
11419 	}
11420 
11421 	prm = &sp->param[0];
11422 
11423 	for (ix = 0; rval == 0 && ix < TAPE_SEQUENTIAL_PAGE_PARA; ix++) {
11424 
11425 		if (prm->log_param.length == 0) {
11426 			break;
11427 		}
11428 
11429 		parameter = (((prm->log_param.pc_hi << 8) & 0xff00) +
11430 		    (prm->log_param.pc_lo & 0xff));
11431 
11432 		if (parameter == SEQUENTIAL_NEED_CLN) {
11433 
11434 			rval = MTF_TAPE_CLN_SUPPORTED;
11435 			if (prm->param_value[prm->log_param.length - 1]) {
11436 
11437 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11438 				    "sequential log says head dirty\n");
11439 				rval |= MTF_TAPE_HEAD_DIRTY;
11440 			}
11441 		}
11442 		prm = (struct log_sequential_page_parameter *)
11443 		    &prm->param_value[prm->log_param.length];
11444 	}
11445 
11446 	kmem_free(cmd, sizeof (struct uscsi_cmd));
11447 	kmem_free(sp,  sizeof (struct log_sequential_page));
11448 
11449 	return (rval);
11450 }
11451 
11452 
11453 static int
11454 st_check_alert_flags(dev_t dev)
11455 {
11456 	struct st_tape_alert *ta;
11457 	struct uscsi_cmd *com;
11458 	unsigned ix, length;
11459 	int rval;
11460 	tape_alert_flags flag;
11461 	char cdb[CDB_GROUP1] = {
11462 		SCMD_LOG_SENSE_G1,
11463 		0,
11464 		TAPE_ALERT_PAGE | CURRENT_THRESHOLD_VALUES,
11465 		0,
11466 		0,
11467 		0,
11468 		0,
11469 		(char)(sizeof (struct st_tape_alert) >> 8),
11470 		(char)(sizeof (struct st_tape_alert)),
11471 		0
11472 	};
11473 
11474 	GET_SOFT_STATE(dev);
11475 
11476 	ST_FUNC(ST_DEVINFO, st_check_alert_clean_bit);
11477 
11478 	com = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
11479 	ta  = kmem_zalloc(sizeof (struct st_tape_alert), KM_SLEEP);
11480 
11481 	com->uscsi_cdb = cdb;
11482 	com->uscsi_cdblen = CDB_GROUP1;
11483 	com->uscsi_bufaddr = (caddr_t)ta;
11484 	com->uscsi_buflen = sizeof (struct st_tape_alert);
11485 	com->uscsi_flags =
11486 	    USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
11487 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
11488 
11489 	rval = st_ioctl_cmd(dev, com, FKIOCTL);
11490 
11491 	if (rval || com->uscsi_status || com->uscsi_resid) {
11492 
11493 		rval = -1; /* uscsi-command failed */
11494 
11495 	} else if (ta->log_page.code != TAPE_ALERT_PAGE) {
11496 
11497 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11498 		"Not Alert Log Page returned 0x%X\n", ta->log_page.code);
11499 		rval = -1;
11500 	}
11501 
11502 	length = (ta->log_page.length_hi << 8) + ta->log_page.length_lo;
11503 
11504 
11505 	if (length != TAPE_ALERT_PARAMETER_LENGTH) {
11506 
11507 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11508 		    "TapeAlert length %d\n", length);
11509 	}
11510 
11511 
11512 	for (ix = 0; ix < TAPE_ALERT_MAX_PARA; ix++) {
11513 
11514 		/*
11515 		 * if rval is bad before the first pass don't bother
11516 		 */
11517 		if (ix == 0 && rval != 0) {
11518 
11519 			break;
11520 		}
11521 
11522 		flag = ((ta->param[ix].log_param.pc_hi << 8) +
11523 		    ta->param[ix].log_param.pc_lo);
11524 
11525 		if ((ta->param[ix].param_value & 1) == 0) {
11526 			continue;
11527 		}
11528 		/*
11529 		 * check to see if current parameter is of interest.
11530 		 * CLEAN_FOR_ERRORS is vendor specific to 9840 9940 stk's.
11531 		 */
11532 		if ((flag == TAF_CLEAN_NOW) ||
11533 		    (flag == TAF_CLEAN_PERIODIC) ||
11534 		    ((flag == CLEAN_FOR_ERRORS) &&
11535 		    (un->un_dp->type == ST_TYPE_STK9840))) {
11536 
11537 			rval = MTF_TAPE_CLN_SUPPORTED;
11538 
11539 
11540 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11541 			    "alert_page drive needs clean %d\n", flag);
11542 			un->un_HeadClean |= TAPE_ALERT_STILL_DIRTY;
11543 			rval |= MTF_TAPE_HEAD_DIRTY;
11544 
11545 		} else if (flag == TAF_CLEANING_MEDIA) {
11546 
11547 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11548 			    "alert_page drive was cleaned\n");
11549 			un->un_HeadClean &= ~TAPE_ALERT_STILL_DIRTY;
11550 		}
11551 
11552 	}
11553 
11554 	/*
11555 	 * Report it as dirty till we see it cleaned
11556 	 */
11557 	if (un->un_HeadClean & TAPE_ALERT_STILL_DIRTY) {
11558 
11559 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11560 		    "alert_page still dirty\n");
11561 		rval |= MTF_TAPE_HEAD_DIRTY;
11562 	}
11563 
11564 	kmem_free(com, sizeof (struct uscsi_cmd));
11565 	kmem_free(ta,  sizeof (struct st_tape_alert));
11566 
11567 	return (rval);
11568 }
11569 
11570 
11571 static int
11572 st_check_sense_clean_bit(dev_t dev)
11573 {
11574 	uchar_t *sensep;
11575 	char cdb[CDB_GROUP0];
11576 	struct uscsi_cmd *com;
11577 	ushort_t byte_pos;
11578 	uchar_t bit_mask;
11579 	unsigned length;
11580 	int index;
11581 	int rval;
11582 
11583 	GET_SOFT_STATE(dev);
11584 
11585 	ST_FUNC(ST_DEVINFO, st_check_sense_clean_bit);
11586 
11587 	/*
11588 	 * Since this tape does not support Tape Alert,
11589 	 * we now try to get the cleanbit status via
11590 	 * Request Sense.
11591 	 */
11592 
11593 	if ((un->un_dp->options & ST_CLN_MASK) == ST_CLN_TYPE_1) {
11594 
11595 		index = 0;
11596 
11597 	} else if ((un->un_dp->options & ST_CLN_MASK) == ST_CLN_TYPE_2) {
11598 
11599 		index = 1;
11600 
11601 	} else if ((un->un_dp->options & ST_CLN_MASK) == ST_CLN_TYPE_3) {
11602 
11603 		index = 2;
11604 
11605 	} else {
11606 
11607 		return (-1);
11608 	}
11609 
11610 	byte_pos  = st_cln_bit_position[index].cln_bit_byte;
11611 	bit_mask  = st_cln_bit_position[index].cln_bit_mask;
11612 	length = byte_pos + 1;
11613 
11614 	com    = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
11615 	sensep = kmem_zalloc(length, KM_SLEEP);
11616 
11617 	cdb[0] = SCMD_REQUEST_SENSE;
11618 	cdb[1] = 0;
11619 	cdb[2] = 0;
11620 	cdb[3] = 0;
11621 	cdb[4] = (char)length;
11622 	cdb[5] = 0;
11623 
11624 	com->uscsi_cdb = cdb;
11625 	com->uscsi_cdblen = CDB_GROUP0;
11626 	com->uscsi_bufaddr = (caddr_t)sensep;
11627 	com->uscsi_buflen = length;
11628 	com->uscsi_flags =
11629 	    USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
11630 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
11631 
11632 	rval = st_ioctl_cmd(dev, com, FKIOCTL);
11633 
11634 	if (rval || com->uscsi_status || com->uscsi_resid) {
11635 
11636 		rval = -1;
11637 
11638 	} else {
11639 
11640 		rval = MTF_TAPE_CLN_SUPPORTED;
11641 		if ((sensep[byte_pos] & bit_mask) == bit_mask) {
11642 
11643 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11644 			    "sense data says head dirty\n");
11645 			rval |= MTF_TAPE_HEAD_DIRTY;
11646 		}
11647 	}
11648 
11649 	kmem_free(com, sizeof (struct uscsi_cmd));
11650 	kmem_free(sensep, length);
11651 	return (rval);
11652 }
11653 
11654 /*
11655  * st_clear_unit_attention
11656  *
11657  *  	run test unit ready's to clear out outstanding
11658  * 	unit attentions.
11659  * 	returns zero for SUCCESS or the errno from st_cmd call
11660  */
11661 static int
11662 st_clear_unit_attentions(dev_t dev_instance, int max_trys)
11663 {
11664 	int	i    = 0;
11665 	int	rval;
11666 
11667 #ifdef DEBUG
11668 	GET_SOFT_STATE(dev_instance);
11669 	ST_FUNC(ST_DEVINFO, st_clear_unit_attentions);
11670 #endif
11671 
11672 	do {
11673 		rval = st_cmd(dev_instance, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
11674 	} while ((rval != 0) && (rval != ENXIO) && (++i < max_trys));
11675 	return (rval);
11676 }
11677 
11678 static void
11679 st_calculate_timeouts(struct scsi_tape *un)
11680 {
11681 	ST_FUNC(ST_DEVINFO, st_calculate_timeouts);
11682 
11683 	if (un->un_dp->non_motion_timeout == 0) {
11684 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
11685 			un->un_dp->non_motion_timeout =
11686 			    st_io_time * st_long_timeout_x;
11687 		} else {
11688 			un->un_dp->non_motion_timeout = (ushort_t)st_io_time;
11689 		}
11690 	}
11691 
11692 	if (un->un_dp->io_timeout == 0) {
11693 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
11694 			un->un_dp->io_timeout = st_io_time * st_long_timeout_x;
11695 		} else {
11696 			un->un_dp->io_timeout = (ushort_t)st_io_time;
11697 		}
11698 	}
11699 
11700 	if (un->un_dp->rewind_timeout == 0) {
11701 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
11702 			un->un_dp->rewind_timeout =
11703 			    st_space_time * st_long_timeout_x;
11704 		} else {
11705 			un->un_dp->rewind_timeout = (ushort_t)st_space_time;
11706 		}
11707 	}
11708 
11709 	if (un->un_dp->space_timeout == 0) {
11710 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
11711 			un->un_dp->space_timeout =
11712 			    st_space_time * st_long_timeout_x;
11713 		} else {
11714 			un->un_dp->space_timeout = (ushort_t)st_space_time;
11715 		}
11716 	}
11717 
11718 	if (un->un_dp->load_timeout == 0) {
11719 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
11720 			un->un_dp->load_timeout =
11721 			    st_space_time * st_long_timeout_x;
11722 		} else {
11723 			un->un_dp->load_timeout = (ushort_t)st_space_time;
11724 		}
11725 	}
11726 
11727 	if (un->un_dp->unload_timeout == 0) {
11728 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
11729 			un->un_dp->unload_timeout =
11730 			    st_space_time * st_long_timeout_x;
11731 		} else {
11732 			un->un_dp->unload_timeout = (ushort_t)st_space_time;
11733 		}
11734 	}
11735 
11736 	if (un->un_dp->erase_timeout == 0) {
11737 		if (un->un_dp->options & ST_LONG_ERASE) {
11738 			un->un_dp->erase_timeout =
11739 			    st_space_time * st_long_space_time_x;
11740 		} else {
11741 			un->un_dp->erase_timeout = (ushort_t)st_space_time;
11742 		}
11743 	}
11744 }
11745 
11746 
11747 static writablity
11748 st_is_not_wormable(struct scsi_tape *un)
11749 {
11750 	ST_FUNC(ST_DEVINFO, st_is_not_wormable);
11751 	return (RDWR);
11752 }
11753 
11754 static writablity
11755 st_is_hp_lto_tape_worm(struct scsi_tape *un)
11756 {
11757 	writablity wrt;
11758 
11759 	ST_FUNC(ST_DEVINFO, st_is_hp_lto_tape_worm);
11760 
11761 	/* Mode sense should be current */
11762 	switch (un->un_mspl->media_type) {
11763 	case 0x00:
11764 		switch (un->un_mspl->density) {
11765 		case 0x40:
11766 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11767 			    "Drive has standard Gen I media loaded\n");
11768 			break;
11769 		case 0x42:
11770 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11771 			    "Drive has standard Gen II media loaded\n");
11772 			break;
11773 		case 0x44:
11774 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11775 			    "Drive has standard Gen III media loaded\n");
11776 			break;
11777 		case 0x46:
11778 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11779 			    "Drive has standard Gen IV media loaded\n");
11780 			break;
11781 		default:
11782 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11783 			    "Drive has standard unknown 0x%X media loaded\n",
11784 			    un->un_mspl->density);
11785 		}
11786 		wrt = RDWR;
11787 		break;
11788 	case 0x01:
11789 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11790 		    "Drive has WORM medium loaded\n");
11791 		wrt = WORM;
11792 		break;
11793 	case 0x80:
11794 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11795 		    "Drive has CD-ROM emulation medium loaded\n");
11796 		wrt = WORM;
11797 		break;
11798 	default:
11799 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11800 		    "Drive has an unexpected medium type 0x%X loaded\n",
11801 		    un->un_mspl->media_type);
11802 		wrt = RDWR;
11803 	}
11804 
11805 	return (wrt);
11806 }
11807 
11808 #define	LTO_REQ_INQUIRY 44
11809 static writablity
11810 st_is_hp_lto_worm(struct scsi_tape *un)
11811 {
11812 	char *buf;
11813 	int result;
11814 	writablity wrt;
11815 
11816 	ST_FUNC(ST_DEVINFO, st_is_hp_lto_worm);
11817 
11818 	buf = kmem_zalloc(LTO_REQ_INQUIRY, KM_SLEEP);
11819 
11820 	result = st_get_special_inquiry(un, LTO_REQ_INQUIRY, buf, 0);
11821 
11822 	if (result != 0) {
11823 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11824 		    "Read Standard Inquiry for WORM support failed");
11825 		wrt = FAILED;
11826 	} else if ((buf[40] & 1) == 0) {
11827 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11828 		    "Drive is NOT WORMable\n");
11829 		/* This drive doesn't support it so don't check again */
11830 		un->un_dp->options &= ~ST_WORMABLE;
11831 		wrt = RDWR;
11832 		un->un_wormable = st_is_not_wormable;
11833 	} else {
11834 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11835 		    "Drive supports WORM version %d\n", buf[40] >> 1);
11836 		un->un_wormable = st_is_hp_lto_tape_worm;
11837 		wrt = un->un_wormable(un);
11838 	}
11839 
11840 	kmem_free(buf, LTO_REQ_INQUIRY);
11841 
11842 	/*
11843 	 * If drive doesn't support it no point in checking further.
11844 	 */
11845 	return (wrt);
11846 }
11847 
11848 static writablity
11849 st_is_t10_worm_device(struct scsi_tape *un)
11850 {
11851 	writablity wrt;
11852 
11853 	ST_FUNC(ST_DEVINFO, st_is_t10_worm_device);
11854 
11855 	if (un->un_mspl->media_type == 0x3c) {
11856 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11857 		    "Drive has WORM media loaded\n");
11858 		wrt = WORM;
11859 	} else {
11860 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11861 		    "Drive has non WORM media loaded\n");
11862 		wrt = RDWR;
11863 	}
11864 	return (wrt);
11865 }
11866 
11867 #define	SEQ_CAP_PAGE	(char)0xb0
11868 static writablity
11869 st_is_t10_worm(struct scsi_tape *un)
11870 {
11871 	char *buf;
11872 	int result;
11873 	writablity wrt;
11874 
11875 	ST_FUNC(ST_DEVINFO, st_is_t10_worm);
11876 
11877 	buf = kmem_zalloc(6, KM_SLEEP);
11878 
11879 	result = st_get_special_inquiry(un, 6, buf, SEQ_CAP_PAGE);
11880 
11881 	if (result != 0) {
11882 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11883 		    "Read Vitial Inquiry for Sequental Capability"
11884 		    " WORM support failed %x", result);
11885 		wrt = FAILED;
11886 	} else if ((buf[4] & 1) == 0) {
11887 		ASSERT(buf[1] == SEQ_CAP_PAGE);
11888 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11889 		    "Drive is NOT WORMable\n");
11890 		/* This drive doesn't support it so don't check again */
11891 		un->un_dp->options &= ~ST_WORMABLE;
11892 		wrt = RDWR;
11893 		un->un_wormable = st_is_not_wormable;
11894 	} else {
11895 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11896 		    "Drive supports WORM\n");
11897 		un->un_wormable = st_is_t10_worm_device;
11898 		wrt = un->un_wormable(un);
11899 	}
11900 
11901 	kmem_free(buf, 6);
11902 
11903 	return (wrt);
11904 }
11905 
11906 
11907 #define	STK_REQ_SENSE 26
11908 
11909 static writablity
11910 st_is_stk_worm(struct scsi_tape *un)
11911 {
11912 	char cdb[CDB_GROUP0] = {SCMD_REQUEST_SENSE, 0, 0, 0, STK_REQ_SENSE, 0};
11913 	struct scsi_extended_sense *sense;
11914 	struct uscsi_cmd *cmd;
11915 	char *buf;
11916 	int result;
11917 	writablity wrt;
11918 
11919 	ST_FUNC(ST_DEVINFO, st_is_stk_worm);
11920 
11921 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
11922 	buf = kmem_alloc(STK_REQ_SENSE, KM_SLEEP);
11923 	sense = (struct scsi_extended_sense *)buf;
11924 
11925 	cmd->uscsi_flags = USCSI_READ;
11926 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
11927 	cmd->uscsi_cdb = &cdb[0];
11928 	cmd->uscsi_bufaddr = buf;
11929 	cmd->uscsi_buflen = STK_REQ_SENSE;
11930 	cmd->uscsi_cdblen = CDB_GROUP0;
11931 	cmd->uscsi_rqlen = 0;
11932 	cmd->uscsi_rqbuf = NULL;
11933 
11934 	result = st_ioctl_cmd(un->un_dev, cmd, FKIOCTL);
11935 
11936 	if (result != 0 || cmd->uscsi_status != 0) {
11937 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11938 		    "Request Sense for WORM failed");
11939 		wrt = RDWR;
11940 	} else if (sense->es_add_len + 8 < 24) {
11941 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11942 		    "Drive didn't send enough sense data for WORM byte %d\n",
11943 		    sense->es_add_len + 8);
11944 		wrt = RDWR;
11945 		un->un_wormable = st_is_not_wormable;
11946 	} else if ((buf[24]) & 0x02) {
11947 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11948 		    "Drive has WORM tape loaded\n");
11949 		wrt = WORM;
11950 		un->un_wormable = st_is_stk_worm;
11951 	} else {
11952 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11953 		    "Drive has normal tape loaded\n");
11954 		wrt = RDWR;
11955 		un->un_wormable = st_is_stk_worm;
11956 	}
11957 
11958 	kmem_free(buf, STK_REQ_SENSE);
11959 	kmem_free(cmd, sizeof (struct uscsi_cmd));
11960 	return (wrt);
11961 }
11962 
11963 #define	DLT_INQ_SZ 44
11964 
11965 static writablity
11966 st_is_dlt_tape_worm(struct scsi_tape *un)
11967 {
11968 	caddr_t buf;
11969 	int result;
11970 	writablity wrt;
11971 
11972 	ST_FUNC(ST_DEVINFO, st_is_dlt_tape_worm);
11973 
11974 	buf = kmem_alloc(DLT_INQ_SZ, KM_SLEEP);
11975 
11976 	/* Read Attribute Media Type */
11977 
11978 	result = st_read_attributes(un, 0x0408, buf, 10);
11979 
11980 	/*
11981 	 * If this quantum drive is attached via an HBA that cannot
11982 	 * support thr read attributes command return error in the
11983 	 * hope that someday they will support the t10 method.
11984 	 */
11985 	if (result == EINVAL && un->un_max_cdb_sz < CDB_GROUP4) {
11986 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
11987 		    "Read Attribute Command for WORM Media detection is not "
11988 		    "supported on the HBA that this drive is attached to.");
11989 		wrt = RDWR;
11990 		un->un_wormable = st_is_not_wormable;
11991 		goto out;
11992 	}
11993 
11994 	if (result != 0) {
11995 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11996 		    "Read Attribute Command for WORM Media returned 0x%x",
11997 		    result);
11998 		wrt = RDWR;
11999 		un->un_dp->options &= ~ST_WORMABLE;
12000 		goto out;
12001 	}
12002 
12003 	if ((uchar_t)buf[9] == 0x80) {
12004 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12005 		    "Drive media is WORM\n");
12006 		wrt = WORM;
12007 	} else {
12008 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12009 		    "Drive media is not WORM Media 0x%x\n", (uchar_t)buf[9]);
12010 		wrt = RDWR;
12011 	}
12012 
12013 out:
12014 	kmem_free(buf, DLT_INQ_SZ);
12015 	return (wrt);
12016 }
12017 
12018 static writablity
12019 st_is_dlt_worm(struct scsi_tape *un)
12020 {
12021 	caddr_t buf;
12022 	int result;
12023 	writablity wrt;
12024 
12025 	ST_FUNC(ST_DEVINFO, st_is_dlt_worm);
12026 
12027 	buf = kmem_alloc(DLT_INQ_SZ, KM_SLEEP);
12028 
12029 	result = st_get_special_inquiry(un, DLT_INQ_SZ, buf, 0xC0);
12030 
12031 	if (result != 0) {
12032 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12033 		    "Read Vendor Specific Inquiry for WORM support failed");
12034 		wrt = RDWR;
12035 		goto out;
12036 	}
12037 
12038 	if ((buf[2] & 1) == 0) {
12039 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12040 		    "Drive is not WORMable\n");
12041 		wrt = RDWR;
12042 		un->un_dp->options &= ~ST_WORMABLE;
12043 		un->un_wormable = st_is_not_wormable;
12044 		goto out;
12045 	} else {
12046 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12047 		    "Drive is WORMable\n");
12048 		un->un_wormable = st_is_dlt_tape_worm;
12049 		wrt = un->un_wormable(un);
12050 	}
12051 out:
12052 	kmem_free(buf, DLT_INQ_SZ);
12053 
12054 	return (wrt);
12055 }
12056 
12057 typedef struct {
12058 	struct modeheader_seq header;
12059 #if defined(_BIT_FIELDS_LTOH) /* X86 */
12060 	uchar_t pagecode	:6,
12061 				:2;
12062 	uchar_t page_len;
12063 	uchar_t syslogalive	:2,
12064 		device		:1,
12065 		abs		:1,
12066 		ulpbot		:1,
12067 		prth		:1,
12068 		ponej		:1,
12069 		ait		:1;
12070 	uchar_t span;
12071 
12072 	uchar_t			:6,
12073 		worm		:1,
12074 		mic		:1;
12075 	uchar_t worm_cap	:1,
12076 				:7;
12077 	uint32_t		:32;
12078 #else /* SPARC */
12079 	uchar_t			:2,
12080 		pagecode	:6;
12081 	uchar_t page_len;
12082 	uchar_t ait		:1,
12083 		device		:1,
12084 		abs		:1,
12085 		ulpbot		:1,
12086 		prth		:1,
12087 		ponej		:1,
12088 		syslogalive	:2;
12089 	uchar_t span;
12090 	uchar_t mic		:1,
12091 		worm		:1,
12092 				:6;
12093 	uchar_t			:7,
12094 		worm_cap	:1;
12095 	uint32_t		:32;
12096 #endif
12097 }ait_dev_con;
12098 
12099 #define	AIT_DEV_PAGE 0x31
12100 static writablity
12101 st_is_sony_worm(struct scsi_tape *un)
12102 {
12103 	int result;
12104 	writablity wrt;
12105 	ait_dev_con *ait_conf;
12106 
12107 	ST_FUNC(ST_DEVINFO, st_is_sony_worm);
12108 
12109 	ait_conf = kmem_zalloc(sizeof (ait_dev_con), KM_SLEEP);
12110 
12111 	result = st_gen_mode_sense(un, AIT_DEV_PAGE,
12112 	    (struct seq_mode *)ait_conf, sizeof (ait_dev_con));
12113 
12114 	if (result == 0) {
12115 
12116 		if (ait_conf->pagecode != AIT_DEV_PAGE) {
12117 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12118 			    "returned page 0x%x not 0x%x AIT_DEV_PAGE\n",
12119 			    ait_conf->pagecode, AIT_DEV_PAGE);
12120 			wrt = RDWR;
12121 			un->un_wormable = st_is_not_wormable;
12122 
12123 		} else if (ait_conf->worm_cap) {
12124 
12125 			un->un_wormable = st_is_sony_worm;
12126 
12127 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12128 			    "Drives is WORMable\n");
12129 			if (ait_conf->worm) {
12130 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12131 				    "Media is WORM\n");
12132 				wrt = WORM;
12133 			} else {
12134 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12135 				    "Media is not WORM\n");
12136 				wrt = RDWR;
12137 			}
12138 
12139 		} else {
12140 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12141 			    "Drives not is WORMable\n");
12142 			wrt = RDWR;
12143 			/* No further checking required */
12144 			un->un_dp->options &= ~ST_WORMABLE;
12145 		}
12146 
12147 	} else {
12148 
12149 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12150 		    "AIT device config mode sense page read command failed"
12151 		    " result = %d ", result);
12152 		wrt = FAILED;
12153 		un->un_wormable = st_is_not_wormable;
12154 	}
12155 
12156 	kmem_free(ait_conf, sizeof (ait_dev_con));
12157 	return (wrt);
12158 }
12159 
12160 static writablity
12161 st_is_drive_worm(struct scsi_tape *un)
12162 {
12163 	writablity wrt;
12164 
12165 	ST_FUNC(ST_DEVINFO, st_is_sony_worm);
12166 
12167 	switch (un->un_dp->type) {
12168 	case MT_ISDLT:
12169 		wrt = st_is_dlt_worm(un);
12170 		break;
12171 
12172 	case MT_ISSTK9840:
12173 		wrt = st_is_stk_worm(un);
12174 		break;
12175 
12176 	case MT_IS8MM:
12177 	case MT_ISAIT:
12178 		wrt = st_is_sony_worm(un);
12179 		break;
12180 
12181 	case MT_LTO:
12182 		if (strncmp("HP ", un->un_dp->vid, 3) == 0) {
12183 			wrt = st_is_hp_lto_worm(un);
12184 		} else {
12185 			wrt = st_is_t10_worm(un);
12186 		}
12187 		break;
12188 
12189 	default:
12190 		wrt = FAILED;
12191 		break;
12192 	}
12193 
12194 	/*
12195 	 * If any of the above failed try the t10 standard method.
12196 	 */
12197 	if (wrt == FAILED) {
12198 		wrt = st_is_t10_worm(un);
12199 	}
12200 
12201 	/*
12202 	 * Unknown method for detecting WORM media.
12203 	 */
12204 	if (wrt == FAILED) {
12205 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12206 		    "Unknown method for WORM media detection\n");
12207 		wrt = RDWR;
12208 		un->un_dp->options &= ~ST_WORMABLE;
12209 	}
12210 
12211 	return (wrt);
12212 }
12213 
12214 static int
12215 st_read_attributes(struct scsi_tape *un, uint16_t attribute, caddr_t buf,
12216     size_t size)
12217 {
12218 	char cdb[CDB_GROUP4];
12219 	int result;
12220 	struct uscsi_cmd *cmd;
12221 
12222 	ST_FUNC(ST_DEVINFO, st_read_attributes);
12223 
12224 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
12225 
12226 	cdb[0] = (char)SCMD_READ_ATTRIBUTE;
12227 	cdb[1] = 0;
12228 	cdb[2] = 0;
12229 	cdb[3] = 0;
12230 	cdb[4] = 0;
12231 	cdb[5] = 0;
12232 	cdb[6] = 0;
12233 	cdb[7] = 0;
12234 	cdb[8] = (char)(attribute >> 8);
12235 	cdb[9] = (char)(attribute);
12236 	cdb[10] = (char)(size >> 24);
12237 	cdb[11] = (char)(size >> 16);
12238 	cdb[12] = (char)(size >> 8);
12239 	cdb[13] = (char)(size);
12240 	cdb[14] = 0;
12241 	cdb[15] = 0;
12242 
12243 
12244 	cmd->uscsi_flags = USCSI_READ | USCSI_DIAGNOSE;
12245 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
12246 	cmd->uscsi_cdb = &cdb[0];
12247 	cmd->uscsi_bufaddr = (caddr_t)buf;
12248 	cmd->uscsi_buflen = size;
12249 	cmd->uscsi_cdblen = sizeof (cdb);
12250 
12251 	result = st_ioctl_cmd(un->un_dev, cmd, FKIOCTL);
12252 
12253 	if (result != 0 || cmd->uscsi_status != 0) {
12254 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12255 		    "st_read_attribute failed: result %d status %d\n",
12256 		    result, cmd->uscsi_status);
12257 		if (result == 0) {
12258 			result = EIO;
12259 		}
12260 		goto exit;
12261 	}
12262 
12263 	/*
12264 	 * The attribute retured should match the attribute requested.
12265 	 */
12266 	if (buf[4] != cdb[8] || buf[5] != cdb[9]) {
12267 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
12268 		    "bad? data", buf, size);
12269 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
12270 		    "st_read_attribute got wrong data back expected 0x%x"
12271 		    " got 0x%x\n", attribute, buf[6] << 8 | buf[7]);
12272 		result = EIO;
12273 	}
12274 exit:
12275 	kmem_free(cmd, sizeof (struct uscsi_cmd));
12276 
12277 	return (result);
12278 }
12279 
12280 static int
12281 st_get_special_inquiry(struct scsi_tape *un, uchar_t size, caddr_t dest,
12282     uchar_t page)
12283 {
12284 	char cdb[CDB_GROUP0];
12285 	struct scsi_extended_sense *sense;
12286 	struct uscsi_cmd *cmd;
12287 	int result;
12288 
12289 	ST_FUNC(ST_DEVINFO, st_get_special_inquiry);
12290 
12291 	cdb[0] = SCMD_INQUIRY;
12292 	cdb[1] = page ? 1 : 0;
12293 	cdb[2] = page;
12294 	cdb[3] = 0;
12295 	cdb[4] = size;
12296 	cdb[5] = 0;
12297 
12298 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
12299 	sense = kmem_alloc(sizeof (struct scsi_extended_sense), KM_SLEEP);
12300 
12301 	cmd->uscsi_flags = USCSI_READ | USCSI_RQENABLE;
12302 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
12303 	cmd->uscsi_cdb = &cdb[0];
12304 	cmd->uscsi_bufaddr = dest;
12305 	cmd->uscsi_buflen = size;
12306 	cmd->uscsi_cdblen = CDB_GROUP0;
12307 	cmd->uscsi_rqlen = sizeof (struct scsi_extended_sense);
12308 	cmd->uscsi_rqbuf = (caddr_t)sense;
12309 
12310 	result = st_ioctl_cmd(un->un_dev, cmd, FKIOCTL);
12311 
12312 	if (result != 0 || cmd->uscsi_status != 0) {
12313 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12314 		    "st_get_special_inquiry() failed for page %x", page);
12315 		if (result == 0) {
12316 			result = EIO;
12317 		}
12318 	}
12319 
12320 	kmem_free(sense, sizeof (struct scsi_extended_sense));
12321 	kmem_free(cmd, sizeof (struct uscsi_cmd));
12322 
12323 	return (result);
12324 }
12325 
12326 
12327 static int
12328 st_update_block_pos(struct scsi_tape *un)
12329 {
12330 	int rval = ENOTTY;
12331 
12332 	ST_FUNC(ST_DEVINFO, st_update_block_pos);
12333 
12334 	while (un->un_read_pos_type != NO_POS) {
12335 		rval = st_cmd(un->un_dev, SCMD_READ_POSITION, 32, SYNC_CMD);
12336 
12337 		if (rval == 0) {
12338 			rval = st_interpret_read_pos(un, un->un_read_pos_type,
12339 			    32, (caddr_t)un->un_read_pos_data);
12340 			break;
12341 		} else if (un->un_status == KEY_UNIT_ATTENTION) {
12342 			continue;
12343 		} else if (un->un_status != KEY_ILLEGAL_REQUEST) {
12344 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
12345 			    "st_update_block_pos() read position cmd %x"
12346 			    " returned %x un_status = %d",
12347 			    un->un_read_pos_type, rval, un->un_status);
12348 			break;
12349 		} else {
12350 			ST_DEBUG4(ST_DEVINFO, st_label, CE_NOTE,
12351 			    "st_update_block_pos() read position cmd %x"
12352 			    " returned %x", un->un_read_pos_type, rval);
12353 		}
12354 
12355 		switch (un->un_read_pos_type) {
12356 		case SHORT_POS:
12357 			un->un_read_pos_type = NO_POS;
12358 			break;
12359 
12360 		case LONG_POS:
12361 			un->un_read_pos_type = EXT_POS;
12362 			break;
12363 
12364 		case EXT_POS:
12365 			un->un_read_pos_type = SHORT_POS;
12366 			break;
12367 
12368 		default:
12369 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
12370 			    "Unexpected read position type 0x%x",
12371 			    un->un_read_pos_type);
12372 		}
12373 	}
12374 
12375 	return (rval);
12376 }
12377 
12378 static int
12379 st_get_read_pos(struct scsi_tape *un, buf_t *bp)
12380 {
12381 	int result;
12382 	size_t d_sz;
12383 	caddr_t pos_info;
12384 	struct uscsi_cmd *cmd = (struct uscsi_cmd *)bp->b_back;
12385 
12386 	ST_FUNC(ST_DEVINFO, st_get_read_pos);
12387 
12388 	if (cmd->uscsi_bufaddr == NULL || cmd->uscsi_buflen <= 0) {
12389 		return (0);
12390 	}
12391 
12392 	if (bp_mapin_common(bp, VM_NOSLEEP) == NULL) {
12393 
12394 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
12395 		    "bp_mapin_common() failed");
12396 
12397 		return (EIO);
12398 	}
12399 
12400 	pos_info = bp->b_un.b_addr;
12401 	d_sz = bp->b_bcount - bp->b_resid;
12402 
12403 #ifdef DEBUG
12404 	if ((st_debug & 0xf) > 2) {
12405 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
12406 		    "st_get_read_pos() position info",
12407 		    pos_info, bp->b_bcount);
12408 	}
12409 #endif
12410 
12411 	result = st_interpret_read_pos(un, cmd->uscsi_cdb[1], d_sz, pos_info);
12412 
12413 	bp_mapout(bp);
12414 
12415 	return (result);
12416 }
12417 
12418 #if defined(_BIG_ENDIAN)
12419 
12420 #define	FIX_ENDIAN32(x)
12421 #define	FIX_ENDIAN64(x)
12422 
12423 #elif defined(_LITTLE_ENDIAN)
12424 
12425 static void
12426 st_swap32(uint32_t *val)
12427 {
12428 	uint32_t tmp;
12429 
12430 	tmp =  (*val >> 24) & 0xff;
12431 	tmp |= (*val >>  8) & 0xff00;
12432 	tmp |= (*val <<  8) & 0xff0000;
12433 	tmp |= (*val << 24) & 0xff000000;
12434 
12435 	*val = tmp;
12436 }
12437 
12438 static void
12439 st_swap64(uint64_t *val)
12440 {
12441 	uint32_t low;
12442 	uint32_t high;
12443 
12444 	low =  (uint32_t)(*val);
12445 	high = (uint32_t)(*val >> 32);
12446 
12447 	st_swap32(&low);
12448 	st_swap32(&high);
12449 
12450 	*val =  high;
12451 	*val |= ((uint64_t)low << 32);
12452 }
12453 
12454 #define	FIX_ENDIAN32(x) st_swap32(x)
12455 #define	FIX_ENDIAN64(x) st_swap64(x)
12456 #endif
12457 
12458 static int
12459 st_interpret_read_pos(struct scsi_tape *un, read_p_types type,
12460     size_t data_sz, caddr_t responce)
12461 {
12462 	int rval = 0;
12463 
12464 	ST_FUNC(ST_DEVINFO, st_interpret_read_pos);
12465 
12466 	/*
12467 	 * Look at byte 1 of cdb to see what kind of read position
12468 	 * was requested.
12469 	 */
12470 	switch (type) {
12471 
12472 	case SHORT_POS: /* Short data format */
12473 	{
12474 		tape_position_t *pos_info = (tape_position_t *)responce;
12475 		uint32_t value;
12476 
12477 		/* If reserved fields are non zero don't use the data */
12478 		if (pos_info->reserved0 || pos_info->reserved1 ||
12479 		    pos_info->reserved2[0] || pos_info->reserved2[1] ||
12480 		    pos_info->reserved3) {
12481 			rval = EIO;
12482 			break;
12483 		}
12484 		/*
12485 		 * Position is to large to use this type of read position.
12486 		 */
12487 		if (pos_info->posi_err == 1) {
12488 			rval = ERANGE;
12489 			break;
12490 		}
12491 
12492 		if (pos_info->blk_posi_unkwn == 0) {
12493 
12494 			if (un->un_pos.partition !=
12495 			    pos_info->partition_number) {
12496 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
12497 				    "SHORT_POS current partition %d read %d\n",
12498 				    un->un_pos.partition,
12499 				    pos_info->partition_number);
12500 			}
12501 			un->un_pos.partition = pos_info->partition_number;
12502 			value = pos_info->host_block;
12503 			FIX_ENDIAN32(&value);
12504 
12505 			if (un->un_pos.lgclblkno != value) {
12506 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
12507 				    "SHORT_POS current logical 0x%"PRIx64" read"
12508 				    " 0x%x\n", un->un_pos.lgclblkno, value);
12509 			}
12510 
12511 			un->un_pos.lgclblkno = (uint64_t)value;
12512 
12513 			if (pos_info->begin_of_part && pos_info->end_of_part) {
12514 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
12515 				    "SHORT_POS returned begin and end of"
12516 				    " partition\n");
12517 				break;
12518 			}
12519 			/* Is drive rewound */
12520 			if ((pos_info->begin_of_part == 1) &&
12521 			    (pos_info->host_block == 0)) {
12522 				un->un_pos.blkno = 0;
12523 				un->un_pos.fileno = 0;
12524 				un->un_pos.pmode = legacy;
12525 			} else if (un->un_pos.pmode == invalid) {
12526 				/* If we were lost now were found */
12527 				un->un_pos.pmode = logical;
12528 			}
12529 		} else {
12530 			un->un_pos.pmode = invalid;
12531 		}
12532 		break;
12533 	}
12534 
12535 	case LONG_POS: /* Long data format */
12536 	{
12537 		uint64_t value;
12538 		tape_position_long_t *long_pos_info =
12539 		    (tape_position_long_t *)responce;
12540 
12541 		/* If reserved fields are non zero don't use the data */
12542 		if ((long_pos_info->reserved0) ||
12543 		    (long_pos_info->reserved1) ||
12544 		    (long_pos_info->reserved2)) {
12545 			rval = EIO;
12546 			break;
12547 		}
12548 
12549 		/* Is position Valid */
12550 		if (long_pos_info->blk_posi_unkwn == 0) {
12551 			uint32_t part;
12552 
12553 			part = long_pos_info->partition;
12554 			FIX_ENDIAN32(&part);
12555 			if (un->un_pos.partition != part) {
12556 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
12557 				    "LONG_POS current partition %d"
12558 				    " read %d\n", un->un_pos.partition, part);
12559 			}
12560 			un->un_pos.partition = part;
12561 			value = long_pos_info->block_number;
12562 			FIX_ENDIAN64(&value);
12563 			if (un->un_pos.lgclblkno != value) {
12564 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
12565 				    "LONG_POS current logical 0x%"PRIx64
12566 				    " read 0x%"PRIx64"\n",
12567 				    un->un_pos.lgclblkno, value);
12568 			}
12569 			un->un_pos.lgclblkno = value;
12570 
12571 			if (long_pos_info->begin_of_part &&
12572 			    long_pos_info->end_of_part) {
12573 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
12574 				    "LONG_POS returned begin and end of"
12575 				    " partition\n");
12576 				break;
12577 			}
12578 			if ((long_pos_info->begin_of_part == 1) &&
12579 			    (long_pos_info->block_number == 0)) {
12580 				un->un_pos.blkno = 0;
12581 				un->un_pos.fileno = 0;
12582 				un->un_pos.pmode = legacy;
12583 			} else if (un->un_pos.pmode == invalid) {
12584 				un->un_pos.pmode = logical;
12585 			}
12586 		} else {
12587 			/*
12588 			 * If the drive doesn't know location,
12589 			 * we don't either.
12590 			 */
12591 			un->un_pos.pmode = invalid;
12592 		}
12593 
12594 		value = long_pos_info->file_number;
12595 		FIX_ENDIAN64(&value);
12596 		/* Is file position valid */
12597 		if (long_pos_info->mrk_posi_unkwn == 0) {
12598 			if (((un->un_pos.pmode == legacy) ||
12599 			    (un->un_pos.pmode == logical)) &&
12600 			    (un->un_pos.fileno != value)) {
12601 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
12602 				    "LONG_POS fileno 0x%"PRIx64
12603 				    " not un_pos %x\n", value,
12604 				    un->un_pos.fileno);
12605 			} else if (un->un_pos.pmode == invalid) {
12606 				un->un_pos.pmode = logical;
12607 			}
12608 			un->un_pos.fileno = (int32_t)value;
12609 		} else {
12610 			/*
12611 			 * If the drive doesn't know its position,
12612 			 * we don't either.
12613 			 */
12614 			un->un_pos.pmode = invalid;
12615 		}
12616 		if (un->un_pos.pmode != invalid && long_pos_info->end_of_part) {
12617 			un->un_pos.eof = ST_EOT;
12618 		}
12619 
12620 		break;
12621 	}
12622 
12623 	case EXT_POS: /* Extended data format */
12624 	{
12625 		uint64_t value;
12626 		tape_position_ext_t *ext_pos_info =
12627 		    (tape_position_ext_t *)responce;
12628 
12629 		/* Make sure that there is enough data there */
12630 		if (data_sz < 16) {
12631 			break;
12632 		}
12633 
12634 		/* If reserved fields are non zero don't use the data */
12635 		if (ext_pos_info->reserved0 || ext_pos_info->reserved1) {
12636 			rval = EIO;
12637 			break;
12638 		}
12639 
12640 		/*
12641 		 * In the unlikely event of overflowing 64 bits of position.
12642 		 */
12643 		if (ext_pos_info->posi_err != 0) {
12644 			rval = ERANGE;
12645 			break;
12646 		}
12647 
12648 		/* Is block position information valid */
12649 		if (ext_pos_info->blk_posi_unkwn == 0) {
12650 
12651 			if (un->un_pos.partition != ext_pos_info->partition) {
12652 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
12653 				    "EXT_POS current partition %d read %d\n",
12654 				    un->un_pos.partition,
12655 				    ext_pos_info->partition);
12656 			}
12657 			un->un_pos.partition = ext_pos_info->partition;
12658 
12659 			value = ext_pos_info->host_block;
12660 			FIX_ENDIAN64(&value);
12661 			if (un->un_pos.lgclblkno != value) {
12662 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
12663 				    "EXT_POS current logical 0x%"PRIx64
12664 				    " read 0x%"PRIx64"\n",
12665 				    un->un_pos.lgclblkno, value);
12666 			}
12667 			un->un_pos.lgclblkno = value;
12668 			if ((ext_pos_info->begin_of_part == 1) &&
12669 			    (ext_pos_info->host_block == 0)) {
12670 				un->un_pos.blkno = 0;
12671 				un->un_pos.fileno = 0;
12672 				un->un_pos.pmode = legacy;
12673 			} else if (un->un_pos.pmode == invalid) {
12674 				un->un_pos.pmode = logical;
12675 			}
12676 		} else {
12677 			un->un_pos.pmode = invalid;
12678 		}
12679 		break;
12680 	}
12681 
12682 	default:
12683 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
12684 		    "Got unexpected SCMD_READ_POSITION type %d\n", type);
12685 		rval = EIO;
12686 	}
12687 
12688 	return (rval);
12689 }
12690 
12691 static int
12692 st_logical_block_locate(struct scsi_tape *un, uint64_t lblk, uchar_t partition)
12693 {
12694 	int rval;
12695 	char cdb[CDB_GROUP4];
12696 	struct uscsi_cmd *cmd;
12697 	struct scsi_extended_sense sense;
12698 
12699 	ST_FUNC(ST_DEVINFO, st_logical_block_locate);
12700 
12701 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
12702 
12703 	if (lblk <= INT32_MAX) {
12704 		cmd->uscsi_cdblen = CDB_GROUP1;
12705 		cdb[0] = SCMD_LOCATE;
12706 		cdb[1] = un->un_pos.partition == partition ? 0 : 2;
12707 		cdb[2] = 0;
12708 		cdb[3] = (char)(lblk >> 24);
12709 		cdb[4] = (char)(lblk >> 16);
12710 		cdb[5] = (char)(lblk >> 8);
12711 		cdb[6] = (char)(lblk);
12712 		cdb[7] = 0;
12713 		cdb[8] = partition;
12714 		cdb[9] = 0;
12715 	} else {
12716 		/*
12717 		 * If the drive doesn't give a 64 bit read position data
12718 		 * it is unlikely it will accept 64 bit locates.
12719 		 */
12720 		if (un->un_read_pos_type != LONG_POS) {
12721 			kmem_free(cmd, sizeof (struct uscsi_cmd));
12722 			return (ERANGE);
12723 		}
12724 		cmd->uscsi_cdblen = CDB_GROUP4;
12725 		cdb[0] = (char)SCMD_LOCATE_G4;
12726 		cdb[1] = un->un_pos.partition == partition ? 0 : 2;
12727 		cdb[2] = 0;
12728 		cdb[3] = partition;
12729 		cdb[4] = (char)(lblk >> 56);
12730 		cdb[5] = (char)(lblk >> 48);
12731 		cdb[6] = (char)(lblk >> 40);
12732 		cdb[7] = (char)(lblk >> 32);
12733 		cdb[8] = (char)(lblk >> 24);
12734 		cdb[9] = (char)(lblk >> 16);
12735 		cdb[10] = (char)(lblk >> 8);
12736 		cdb[11] = (char)(lblk);
12737 		cdb[12] = 0;
12738 		cdb[13] = 0;
12739 		cdb[14] = 0;
12740 		cdb[15] = 0;
12741 	}
12742 
12743 
12744 	cmd->uscsi_flags = USCSI_WRITE | USCSI_DIAGNOSE | USCSI_RQENABLE;
12745 	cmd->uscsi_rqbuf = (caddr_t)&sense;
12746 	cmd->uscsi_rqlen = sizeof (sense);
12747 	cmd->uscsi_timeout = un->un_dp->space_timeout;
12748 	cmd->uscsi_cdb = cdb;
12749 
12750 	rval = st_ioctl_cmd(un->un_dev, cmd, FKIOCTL);
12751 
12752 	un->un_pos.pmode = logical;
12753 	un->un_pos.eof = ST_NO_EOF;
12754 
12755 	if (lblk > INT32_MAX) {
12756 		/*
12757 		 * XXX This is a work around till we handle Descriptor format
12758 		 * sense data. Since we are sending a command where the standard
12759 		 * sense data can not correctly represent a correct residual in
12760 		 * 4 bytes.
12761 		 */
12762 		if (un->un_status == KEY_ILLEGAL_REQUEST) {
12763 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
12764 			    "Big LOCATE ILLEGAL_REQUEST: rval = %d\n", rval);
12765 			/* Doesn't like big locate command */
12766 			un->un_status = 0;
12767 			rval = ERANGE;
12768 		} else if ((un->un_pos.pmode == invalid) || (rval != 0)) {
12769 			/* Aborted big locate command */
12770 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
12771 			    "Big LOCATE resulted in invalid pos: rval = %d\n",
12772 			    rval);
12773 			un->un_status = 0;
12774 			rval = EIO;
12775 		} else if (st_update_block_pos(un)) {
12776 			/* read position failed */
12777 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
12778 			    "Big LOCATE and read pos: rval = %d\n", rval);
12779 			rval = EIO;
12780 		} else if (lblk > un->un_pos.lgclblkno) {
12781 			/* read position worked but position was not expected */
12782 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
12783 			    "Big LOCATE and recover read less then desired 0x%"
12784 			    PRIx64"\n", un->un_pos.lgclblkno);
12785 			un->un_err_resid = lblk - un->un_pos.lgclblkno;
12786 			un->un_status = KEY_BLANK_CHECK;
12787 			rval = ESPIPE;
12788 		} else if (lblk == un->un_pos.lgclblkno) {
12789 			/* read position was what was expected */
12790 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
12791 			    "Big LOCATE and recover seems to have worked\n");
12792 			un->un_err_resid = 0;
12793 			rval = 0;
12794 		} else {
12795 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
12796 			    "BIGLOCATE end up going backwards");
12797 			un->un_err_resid = lblk;
12798 			rval = EIO;
12799 		}
12800 
12801 	} else if (rval == 0) {
12802 		/* Worked as requested */
12803 		un->un_pos.lgclblkno = lblk;
12804 
12805 	} else if (((cmd->uscsi_status & STATUS_MASK) == STATUS_CHECK) &&
12806 	    (cmd->uscsi_resid != 0)) {
12807 		/* Got part way there but wasn't enough blocks on tape */
12808 		un->un_pos.lgclblkno = lblk - cmd->uscsi_resid;
12809 		un->un_err_resid = cmd->uscsi_resid;
12810 		un->un_status = KEY_BLANK_CHECK;
12811 		rval = ESPIPE;
12812 
12813 	} else if (st_update_block_pos(un) == 0) {
12814 		/* Got part way there but drive didn't tell what we missed by */
12815 		un->un_err_resid = lblk - un->un_pos.lgclblkno;
12816 		un->un_status = KEY_BLANK_CHECK;
12817 		rval = ESPIPE;
12818 
12819 	} else {
12820 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
12821 		    "Failed LOCATE and recover pos: rval = %d status = %d\n",
12822 		    rval, cmd->uscsi_status);
12823 		un->un_err_resid = lblk;
12824 		un->un_status = KEY_ILLEGAL_REQUEST;
12825 		un->un_pos.pmode = invalid;
12826 		rval = EIO;
12827 	}
12828 
12829 	kmem_free(cmd, sizeof (struct uscsi_cmd));
12830 
12831 	return (rval);
12832 }
12833 
12834 static int
12835 st_mtfsf_ioctl(struct scsi_tape *un, int files)
12836 {
12837 	int rval;
12838 
12839 	ST_FUNC(ST_DEVINFO, st_mtfsf_ioctl);
12840 
12841 
12842 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
12843 	    "st_mtfsf_ioctl: count=%x, eof=%x\n", files, un->un_pos.eof);
12844 
12845 	/* pmode == invalid already handled */
12846 	if (un->un_pos.pmode == legacy) {
12847 		/*
12848 		 * forward space over filemark
12849 		 *
12850 		 * For ASF we allow a count of 0 on fsf which means
12851 		 * we just want to go to beginning of current file.
12852 		 * Equivalent to "nbsf(0)" or "bsf(1) + fsf".
12853 		 * Allow stepping over double fmk with reel
12854 		 */
12855 		if ((un->un_pos.eof >= ST_EOT) &&
12856 		    (files > 0) &&
12857 		    ((un->un_dp->options & ST_REEL) == 0)) {
12858 			/* we're at EOM */
12859 			un->un_err_resid = files;
12860 			un->un_status = KEY_BLANK_CHECK;
12861 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12862 			    "st_mtfsf_ioctl: EIO : MTFSF at EOM");
12863 			return (EIO);
12864 		}
12865 
12866 		/*
12867 		 * physical tape position may not be what we've been
12868 		 * telling the user; adjust the request accordingly
12869 		 */
12870 		if (IN_EOF(un->un_pos)) {
12871 			un->un_pos.fileno++;
12872 			un->un_pos.blkno = 0;
12873 			/*
12874 			 * For positive direction case, we're now covered.
12875 			 * For zero or negative direction, we're covered
12876 			 * (almost)
12877 			 */
12878 			files--;
12879 		}
12880 
12881 	}
12882 
12883 	if (st_check_density_or_wfm(un->un_dev, 1, B_READ, STEPBACK)) {
12884 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12885 		    "st_mtfsf_ioctl: EIO : MTFSF density/wfm failed");
12886 		return (EIO);
12887 	}
12888 
12889 
12890 	/*
12891 	 * Forward space file marks.
12892 	 * We leave ourselves at block zero
12893 	 * of the target file number.
12894 	 */
12895 	if (files < 0) {
12896 		rval = st_backward_space_files(un, -files, 0);
12897 	} else {
12898 		rval = st_forward_space_files(un, files);
12899 	}
12900 
12901 	return (rval);
12902 }
12903 
12904 static int
12905 st_forward_space_files(struct scsi_tape *un, int count)
12906 {
12907 	dev_t dev;
12908 	int rval;
12909 
12910 	ST_FUNC(ST_DEVINFO, st_forward_space_files);
12911 
12912 	dev = un->un_dev;
12913 
12914 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
12915 	    "fspace: count=%x, eof=%x\n", count, un->un_pos.eof);
12916 
12917 	ASSERT(count >= 0);
12918 	ASSERT(un->un_pos.pmode != invalid);
12919 
12920 	/*
12921 	 * A space with a count of zero means take me to the start of file.
12922 	 */
12923 	if (count == 0) {
12924 
12925 		/* Hay look were already there */
12926 		if (un->un_pos.pmode == legacy && un->un_pos.blkno == 0 &&
12927 		    un->un_pos.fileno == 0) {
12928 			un->un_err_resid = 0;
12929 			COPY_POS(&un->un_err_pos, &un->un_pos);
12930 			return (0);
12931 		}
12932 
12933 		/*
12934 		 * Well we are in the first file.
12935 		 * A rewind will get to the start.
12936 		 */
12937 		if (un->un_pos.pmode == legacy && un->un_pos.fileno == 0) {
12938 			rval = st_cmd(dev, SCMD_REWIND, 0, SYNC_CMD);
12939 
12940 		/*
12941 		 * Can we backspace to get there?
12942 		 * This should work in logical mode.
12943 		 */
12944 		} else if (un->un_dp->options & ST_BSF) {
12945 			rval = st_space_to_begining_of_file(un);
12946 
12947 		/*
12948 		 * Can't back space but current file number is known,
12949 		 * So rewind and space from the begining of the partition.
12950 		 */
12951 		} else if (un->un_pos.pmode == legacy) {
12952 			rval = st_scenic_route_to_begining_of_file(un,
12953 			    un->un_pos.fileno);
12954 
12955 		/*
12956 		 * pmode is logical and ST_BSF is not set.
12957 		 * The LONG_POS read position contains the fileno.
12958 		 * If the read position works, rewind and space.
12959 		 */
12960 		} else if (un->un_read_pos_type == LONG_POS) {
12961 			rval = st_cmd(dev, SCMD_READ_POSITION, 0, SYNC_CMD);
12962 			if (rval) {
12963 				/*
12964 				 * We didn't get the file position from the
12965 				 * read position command.
12966 				 * We are going to trust the drive to backspace
12967 				 * and then position after the filemark.
12968 				 */
12969 				rval = st_space_to_begining_of_file(un);
12970 			}
12971 			rval = st_interpret_read_pos(un, LONG_POS, 32,
12972 			    (caddr_t)un->un_read_pos_data);
12973 			if ((rval) && (un->un_pos.pmode == invalid)) {
12974 				rval = st_space_to_begining_of_file(un);
12975 			} else {
12976 				rval = st_scenic_route_to_begining_of_file(un,
12977 				    un->un_pos.fileno);
12978 			}
12979 		} else {
12980 			rval = EIO;
12981 		}
12982 		/*
12983 		 * If something didn't work we are lost
12984 		 */
12985 		if (rval != 0) {
12986 			un->un_pos.pmode = invalid;
12987 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12988 			    "st_mtioctop : EIO : fspace pmode invalid");
12989 
12990 			rval = EIO;
12991 		}
12992 
12993 	} else {
12994 		rval = st_space_fmks(dev, count);
12995 	}
12996 
12997 	if (rval != EIO && count < 0) {
12998 		/*
12999 		 * we came here with a count < 0; we now need
13000 		 * to skip back to end up before the filemark
13001 		 */
13002 		rval = st_backward_space_files(un, 1, 1);
13003 	}
13004 
13005 	return (rval);
13006 }
13007 
13008 static int
13009 st_scenic_route_to_begining_of_file(struct scsi_tape *un, int32_t fileno)
13010 {
13011 	int rval;
13012 
13013 	ST_FUNC(ST_DEVINFO, st_scenic_route_to_begining_of_file);
13014 
13015 	if (st_cmd(un->un_dev, SCMD_REWIND, 0, SYNC_CMD)) {
13016 		rval = EIO;
13017 	} else if (st_cmd(un->un_dev, SCMD_SPACE, Fmk(fileno), SYNC_CMD)) {
13018 		rval = EIO;
13019 	}
13020 
13021 	return (rval);
13022 }
13023 
13024 static int
13025 st_space_to_begining_of_file(struct scsi_tape *un)
13026 {
13027 	int rval;
13028 
13029 	ST_FUNC(ST_DEVINFO, st_space_to_begining_of_file);
13030 
13031 	/*
13032 	 * Back space of the file at the begining of the file.
13033 	 */
13034 	rval = st_cmd(un->un_dev, SCMD_SPACE, Fmk((-1)), SYNC_CMD);
13035 	if (rval) {
13036 		rval = EIO;
13037 		return (rval);
13038 	}
13039 
13040 	/*
13041 	 * Other interesting answers might be crashed BOT which isn't bad.
13042 	 */
13043 	if (un->un_status == SUN_KEY_BOT) {
13044 		return (rval);
13045 	}
13046 
13047 	/*
13048 	 * Now we are on the BOP side of the filemark. Forward space to
13049 	 * the EOM side and we are at the begining of the file.
13050 	 */
13051 	rval = st_cmd(un->un_dev, SCMD_SPACE, Fmk(1), SYNC_CMD);
13052 	if (rval) {
13053 		rval = EIO;
13054 	}
13055 
13056 	return (rval);
13057 }
13058 
13059 static int
13060 st_mtfsr_ioctl(struct scsi_tape *un, int count)
13061 {
13062 
13063 	ST_FUNC(ST_DEVINFO, st_mtfsr_ioctl);
13064 
13065 	/*
13066 	 * forward space to inter-record gap
13067 	 *
13068 	 */
13069 
13070 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13071 	    "st_ioctl_fsr: count=%x, eof=%x\n", count, un->un_pos.eof);
13072 
13073 	if (un->un_pos.pmode == legacy) {
13074 		/*
13075 		 * If were are at end of tape and count is forward.
13076 		 * Return blank check.
13077 		 */
13078 		if ((un->un_pos.eof >= ST_EOT) && (count > 0)) {
13079 			/* we're at EOM */
13080 			un->un_err_resid = count;
13081 			un->un_status = KEY_BLANK_CHECK;
13082 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13083 			    "st_mtfsr_ioctl: EIO : MTFSR eof > ST_EOT");
13084 			return (EIO);
13085 		}
13086 
13087 		/*
13088 		 * If count is zero there is nothing to do.
13089 		 */
13090 		if (count == 0) {
13091 			un->un_err_pos.fileno = un->un_pos.fileno;
13092 			un->un_err_pos.blkno = un->un_pos.blkno;
13093 			un->un_err_resid = 0;
13094 			if (IN_EOF(un->un_pos) && SVR4_BEHAVIOR) {
13095 				un->un_status = SUN_KEY_EOF;
13096 			}
13097 			return (0);
13098 		}
13099 
13100 		/*
13101 		 * physical tape position may not be what we've been
13102 		 * telling the user; adjust the position accordingly
13103 		 */
13104 		if (IN_EOF(un->un_pos)) {
13105 			daddr_t blkno = un->un_pos.blkno;
13106 			int fileno = un->un_pos.fileno;
13107 
13108 			optype lastop = un->un_lastop;
13109 			if (st_cmd(un->un_dev, SCMD_SPACE, Fmk((-1)), SYNC_CMD)
13110 			    == -1) {
13111 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13112 				    "st_mtfsr_ioctl:EIO:MTFSR count && IN_EOF");
13113 				return (EIO);
13114 			}
13115 
13116 			un->un_pos.blkno = blkno;
13117 			un->un_pos.fileno = fileno;
13118 			un->un_lastop = lastop;
13119 		}
13120 	}
13121 
13122 	if (st_check_density_or_wfm(un->un_dev, 1, B_READ, STEPBACK)) {
13123 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13124 		    "st_mtfsr_ioctl: EIO : MTFSR st_check_den");
13125 		return (EIO);
13126 	}
13127 
13128 	return (st_space_records(un, count));
13129 }
13130 
13131 static int
13132 st_space_records(struct scsi_tape *un, int count)
13133 {
13134 	int dblk;
13135 	int rval = 0;
13136 
13137 	ST_FUNC(ST_DEVINFO, st_space_records);
13138 
13139 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13140 	    "st_space_records: count=%x, eof=%x\n", count, un->un_pos.eof);
13141 
13142 	if (un->un_pos.pmode == logical) {
13143 		rval = st_cmd(un->un_dev, SCMD_SPACE, Blk(count), SYNC_CMD);
13144 		if (rval != 0) {
13145 			rval = EIO;
13146 		}
13147 		return (rval);
13148 	}
13149 
13150 	dblk = un->un_pos.blkno + count;
13151 
13152 	/* Already there */
13153 	if (dblk == un->un_pos.blkno) {
13154 		un->un_err_resid = 0;
13155 		COPY_POS(&un->un_err_pos, &un->un_pos);
13156 		return (0);
13157 	}
13158 
13159 	/*
13160 	 * If the destination block is forward
13161 	 * or the drive will backspace records.
13162 	 */
13163 	if (un->un_pos.blkno < dblk || (un->un_dp->options & ST_BSR)) {
13164 		/*
13165 		 * If we're spacing forward, or the device can
13166 		 * backspace records, we can just use the SPACE
13167 		 * command.
13168 		 */
13169 		dblk -= un->un_pos.blkno;
13170 		if (st_cmd(un->un_dev, SCMD_SPACE, Blk(dblk), SYNC_CMD)) {
13171 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13172 			    "st_space_records:EIO:space_records can't spc");
13173 			rval = EIO;
13174 		} else if (un->un_pos.eof >= ST_EOF_PENDING) {
13175 			/*
13176 			 * check if we hit BOT/EOT
13177 			 */
13178 			if (dblk < 0 && un->un_pos.eof == ST_EOM) {
13179 				un->un_status = SUN_KEY_BOT;
13180 				un->un_pos.eof = ST_NO_EOF;
13181 			} else if (dblk < 0 &&
13182 			    un->un_pos.eof == ST_EOF_PENDING) {
13183 				int residue = un->un_err_resid;
13184 				/*
13185 				 * we skipped over a filemark
13186 				 * and need to go forward again
13187 				 */
13188 				if (st_cmd(un->un_dev, SCMD_SPACE, Fmk(1),
13189 				    SYNC_CMD)) {
13190 					ST_DEBUG2(ST_DEVINFO, st_label,
13191 					    SCSI_DEBUG, "st_space_records: EIO"
13192 					    " : can't space #2");
13193 					rval = EIO;
13194 				}
13195 				un->un_err_resid = residue;
13196 			}
13197 			if (rval == 0) {
13198 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13199 				    "st_space_records: EIO : space_rec rval"
13200 				    " == 0");
13201 				rval = EIO;
13202 			}
13203 		}
13204 	} else {
13205 		/*
13206 		 * else we rewind, space forward across filemarks to
13207 		 * the desired file, and then space records to the
13208 		 * desired block.
13209 		 */
13210 
13211 		int dfile = un->un_pos.fileno;	/* save current file */
13212 
13213 		if (dblk < 0) {
13214 			/*
13215 			 * Wups - we're backing up over a filemark
13216 			 */
13217 			if (un->un_pos.blkno != 0 &&
13218 			    (st_cmd(un->un_dev, SCMD_REWIND, 0, SYNC_CMD) ||
13219 			    st_cmd(un->un_dev, SCMD_SPACE, Fmk(dfile),
13220 			    SYNC_CMD))) {
13221 				un->un_pos.pmode = invalid;
13222 			}
13223 			un->un_err_resid = -dblk;
13224 			if (un->un_pos.fileno == 0 && un->un_pos.blkno == 0) {
13225 				un->un_status = SUN_KEY_BOT;
13226 				un->un_pos.eof = ST_NO_EOF;
13227 			} else if (un->un_pos.fileno > 0) {
13228 				un->un_status = SUN_KEY_EOF;
13229 				un->un_pos.eof = ST_NO_EOF;
13230 			}
13231 			COPY_POS(&un->un_err_pos, &un->un_pos);
13232 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13233 			    "st_space_records:EIO:space_records : dblk < 0");
13234 			rval = EIO;
13235 		} else if (st_cmd(un->un_dev, SCMD_REWIND, 0, SYNC_CMD) ||
13236 		    st_cmd(un->un_dev, SCMD_SPACE, Fmk(dfile), SYNC_CMD) ||
13237 		    st_cmd(un->un_dev, SCMD_SPACE, Blk(dblk), SYNC_CMD)) {
13238 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13239 			    "st_space_records: EIO :space_records : rewind "
13240 			    "and space failed");
13241 			un->un_pos.pmode = invalid;
13242 			rval = EIO;
13243 		}
13244 	}
13245 
13246 	return (rval);
13247 }
13248 
13249 static int
13250 st_mtbsf_ioctl(struct scsi_tape *un, int files)
13251 {
13252 	ST_FUNC(ST_DEVINFO, st_mtbsf_ioctl);
13253 
13254 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13255 	    "st_mtbsf_ioctl: count=%x, eof=%x\n", files, un->un_pos.eof);
13256 	/*
13257 	 * backward space of file filemark (1/2" and 8mm)
13258 	 * tape position will end on the beginning of tape side
13259 	 * of the desired file mark
13260 	 */
13261 	if ((un->un_dp->options & ST_BSF) == 0) {
13262 		return (ENOTTY);
13263 	}
13264 
13265 	if (un->un_pos.pmode == legacy) {
13266 
13267 		/*
13268 		 * If a negative count (which implies a forward space op)
13269 		 * is specified, and we're at logical or physical eot,
13270 		 * bounce the request.
13271 		 */
13272 
13273 		if (un->un_pos.eof >= ST_EOT && files < 0) {
13274 			un->un_err_resid = files;
13275 			un->un_status = SUN_KEY_EOT;
13276 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13277 			    "st_ioctl_mt_bsf : EIO : MTBSF : eof > ST_EOF");
13278 			return (EIO);
13279 		}
13280 		/*
13281 		 * physical tape position may not be what we've been
13282 		 * telling the user; adjust the request accordingly
13283 		 */
13284 		if (IN_EOF(un->un_pos)) {
13285 			un->un_pos.fileno++;
13286 			un->un_pos.blkno = 0;
13287 			files++;
13288 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13289 			    "st_mtbsf_ioctl in eof: count=%d, op=%x\n",
13290 			    files, MTBSF);
13291 
13292 		}
13293 	}
13294 
13295 	if (st_check_density_or_wfm(un->un_dev, 1, 0, STEPBACK)) {
13296 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13297 		    "st_ioctl : EIO : MTBSF : check den wfm");
13298 		return (EIO);
13299 	}
13300 
13301 	if (files <= 0) {
13302 		/*
13303 		 * for a negative count, we need to step forward
13304 		 * first and then step back again
13305 		 */
13306 		files = -files + 1;
13307 		return (st_forward_space_files(un, files));
13308 	}
13309 	return (st_backward_space_files(un, files, 1));
13310 }
13311 
13312 static int
13313 st_backward_space_files(struct scsi_tape *un, int count, int infront)
13314 {
13315 	int end_fileno;
13316 	int skip_cnt;
13317 	int rval = 0;
13318 
13319 	ST_FUNC(ST_DEVINFO, st_backward_space_files);
13320 
13321 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13322 	    "st_backward_space_files: count=%x eof=%x\n",
13323 	    count, un->un_pos.eof);
13324 	/*
13325 	 * Backspace files (MTNBSF): infront == 0
13326 	 *
13327 	 *	For tapes that can backspace, backspace
13328 	 *	count+1 filemarks and then run forward over
13329 	 *	a filemark
13330 	 *
13331 	 *	For tapes that can't backspace,
13332 	 *		calculate desired filenumber
13333 	 *		(un->un_pos.fileno - count), rewind,
13334 	 *		and then space forward this amount
13335 	 *
13336 	 * Backspace filemarks (MTBSF) infront == 1
13337 	 *
13338 	 *	For tapes that can backspace, backspace count
13339 	 *	filemarks
13340 	 *
13341 	 *	For tapes that can't backspace, calculate
13342 	 *	desired filenumber (un->un_pos.fileno - count),
13343 	 *	add 1, rewind, space forward this amount,
13344 	 *	and mark state as ST_EOF_PENDING appropriately.
13345 	 */
13346 
13347 	if (un->un_pos.pmode == logical) {
13348 
13349 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13350 		    "st_backward_space_files: mt_op=%x count=%x"
13351 		    "lgclblkno=%"PRIx64"\n", infront?MTBSF:MTNBSF, count,
13352 		    un->un_pos.lgclblkno);
13353 
13354 
13355 		/* In case a drive that won't back space gets in logical mode */
13356 		if ((un->un_dp->options & ST_BSF) == 0) {
13357 			rval = EIO;
13358 			return (rval);
13359 		}
13360 		if (st_cmd(un->un_dev, SCMD_SPACE, Fmk(-count), SYNC_CMD)) {
13361 			rval = EIO;
13362 			return (rval);
13363 		}
13364 		if ((infront != 0) &&
13365 		    (st_cmd(un->un_dev, SCMD_SPACE, Fmk(1), SYNC_CMD))) {
13366 			rval = EIO;
13367 			return (rval);
13368 		}
13369 		return (rval);
13370 	}
13371 
13372 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13373 	    "st_backward_space_files: mt_op=%x count=%x fileno=%x blkno=%x\n",
13374 	    infront?MTBSF:MTNBSF, count, un->un_pos.fileno, un->un_pos.blkno);
13375 
13376 
13377 
13378 	/*
13379 	 * Handle the simple case of BOT
13380 	 * playing a role in these cmds.
13381 	 * We do this by calculating the
13382 	 * ending file number. If the ending
13383 	 * file is < BOT, rewind and set an
13384 	 * error and mark resid appropriately.
13385 	 * If we're backspacing a file (not a
13386 	 * filemark) and the target file is
13387 	 * the first file on the tape, just
13388 	 * rewind.
13389 	 */
13390 
13391 	/* figure expected destination of this SPACE command */
13392 	end_fileno = un->un_pos.fileno - count;
13393 
13394 	/*
13395 	 * Would the end effect of this SPACE be the same as rewinding?
13396 	 * If so just rewind instead.
13397 	 */
13398 	if ((infront != 0) && (end_fileno < 0) ||
13399 	    (infront == 0) && (end_fileno <= 0)) {
13400 		if (st_cmd(un->un_dev, SCMD_REWIND, 0, SYNC_CMD)) {
13401 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13402 			    "st_backward_space_files: EIO : "
13403 			    "rewind in lou of BSF failed\n");
13404 			rval = EIO;
13405 		}
13406 		if (end_fileno < 0) {
13407 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13408 			    "st_backward_space_files: EIO : "
13409 			    "back space file greater then fileno\n");
13410 			rval = EIO;
13411 			un->un_err_resid = -end_fileno;
13412 			un->un_status = SUN_KEY_BOT;
13413 		}
13414 		return (rval);
13415 	}
13416 
13417 	if (un->un_dp->options & ST_BSF) {
13418 		skip_cnt = 1 - infront;
13419 		/*
13420 		 * If we are going to end up at the beginning
13421 		 * of the file, we have to space one extra file
13422 		 * first, and then space forward later.
13423 		 */
13424 		end_fileno = -(count + skip_cnt);
13425 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
13426 		    "skip_cnt=%x, tmp=%x\n", skip_cnt, end_fileno);
13427 		if (st_cmd(un->un_dev, SCMD_SPACE, Fmk(end_fileno), SYNC_CMD)) {
13428 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13429 			    "st_backward_space_files:EIO:back space fm failed");
13430 			rval = EIO;
13431 		}
13432 	} else {
13433 		if (st_cmd(un->un_dev, SCMD_REWIND, 0, SYNC_CMD)) {
13434 			rval = EIO;
13435 		} else {
13436 			skip_cnt = end_fileno + infront;
13437 		}
13438 	}
13439 
13440 	/*
13441 	 * If we have to space forward, do so...
13442 	 */
13443 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
13444 	    "space forward skip_cnt=%x, rval=%x\n", skip_cnt, rval);
13445 
13446 	if (rval == 0 && skip_cnt) {
13447 		if (st_cmd(un->un_dev, SCMD_SPACE, Fmk(skip_cnt), SYNC_CMD)) {
13448 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13449 			    "st_backward_space_files:EIO:space fm skip count");
13450 			rval = EIO;
13451 		} else if (infront) {
13452 			/*
13453 			 * If we had to space forward, and we're
13454 			 * not a tape that can backspace, mark state
13455 			 * as if we'd just seen a filemark during a
13456 			 * a read.
13457 			 */
13458 			if ((un->un_dp->options & ST_BSF) == 0) {
13459 				un->un_pos.eof = ST_EOF_PENDING;
13460 				un->un_pos.fileno -= 1;
13461 				un->un_pos.blkno = INF;
13462 			}
13463 		}
13464 	}
13465 
13466 	if (rval != 0) {
13467 		un->un_pos.pmode = invalid;
13468 	}
13469 
13470 	return (rval);
13471 }
13472 
13473 static int
13474 st_mtnbsf_ioctl(struct scsi_tape *un, int count)
13475 {
13476 	int rval;
13477 
13478 	ST_FUNC(ST_DEVINFO, st_mtnbsf_ioctl);
13479 
13480 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13481 	    "nbsf: count=%x, eof=%x\n", count, un->un_pos.eof);
13482 
13483 	if (un->un_pos.pmode == legacy) {
13484 		/*
13485 		 * backward space file to beginning of file
13486 		 *
13487 		 * If a negative count (which implies a forward space op)
13488 		 * is specified, and we're at logical or physical eot,
13489 		 * bounce the request.
13490 		 */
13491 
13492 		if (un->un_pos.eof >= ST_EOT && count < 0) {
13493 			un->un_err_resid = count;
13494 			un->un_status = SUN_KEY_EOT;
13495 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13496 			    "st_ioctl : EIO : > EOT and count < 0");
13497 			return (EIO);
13498 		}
13499 		/*
13500 		 * physical tape position may not be what we've been
13501 		 * telling the user; adjust the request accordingly
13502 		 */
13503 		if (IN_EOF(un->un_pos)) {
13504 			un->un_pos.fileno++;
13505 			un->un_pos.blkno = 0;
13506 			count++;
13507 		}
13508 	}
13509 
13510 	if (st_check_density_or_wfm(un->un_dev, 1, 0, STEPBACK)) {
13511 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13512 		    "st_ioctl : EIO : MTNBSF check den and wfm");
13513 		return (EIO);
13514 	}
13515 
13516 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13517 	    "mtnbsf: count=%x, eof=%x\n", count, un->un_pos.eof);
13518 
13519 	if (count <= 0) {
13520 		rval = st_forward_space_files(un, -count);
13521 	} else {
13522 		rval = st_backward_space_files(un, count, 0);
13523 	}
13524 	return (rval);
13525 }
13526 
13527 static int
13528 st_mtbsr_ioctl(struct scsi_tape *un, int num)
13529 {
13530 	ST_FUNC(ST_DEVINFO, st_mtbsr_ioctl);
13531 
13532 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13533 	    "bsr: count=%x, eof=%x\n", num, un->un_pos.eof);
13534 
13535 	if (un->un_pos.pmode == legacy) {
13536 		/*
13537 		 * backward space into inter-record gap
13538 		 *
13539 		 * If a negative count (which implies a forward space op)
13540 		 * is specified, and we're at logical or physical eot,
13541 		 * bounce the request.
13542 		 */
13543 		if (un->un_pos.eof >= ST_EOT && num < 0) {
13544 			un->un_err_resid = num;
13545 			un->un_status = SUN_KEY_EOT;
13546 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13547 			    "st_ioctl : EIO : MTBSR > EOT");
13548 			return (EIO);
13549 		}
13550 
13551 		if (num == 0) {
13552 			COPY_POS(&un->un_err_pos, &un->un_pos);
13553 			un->un_err_resid = 0;
13554 			if (IN_EOF(un->un_pos) && SVR4_BEHAVIOR) {
13555 				un->un_status = SUN_KEY_EOF;
13556 			}
13557 			return (0);
13558 		}
13559 
13560 		/*
13561 		 * physical tape position may not be what we've been
13562 		 * telling the user; adjust the position accordingly.
13563 		 * bsr can not skip filemarks and continue to skip records
13564 		 * therefore if we are logically before the filemark but
13565 		 * physically at the EOT side of the filemark, we need to step
13566 		 * back; this allows fsr N where N > number of blocks in file
13567 		 * followed by bsr 1 to position at the beginning of last block
13568 		 */
13569 		if (IN_EOF(un->un_pos)) {
13570 			tapepos_t save;
13571 			optype lastop = un->un_lastop;
13572 
13573 			COPY_POS(&save, &un->un_pos);
13574 			if (st_cmd(un->un_dev, SCMD_SPACE, Fmk((-1)), SYNC_CMD)
13575 			    == -1) {
13576 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13577 				    "st_write_fm : EIO : MTBSR can't space");
13578 				return (EIO);
13579 			}
13580 
13581 			COPY_POS(&un->un_pos, &save);
13582 			un->un_lastop = lastop;
13583 		}
13584 	}
13585 
13586 	un->un_pos.eof = ST_NO_EOF;
13587 
13588 	if (st_check_density_or_wfm(un->un_dev, 1, 0, STEPBACK)) {
13589 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13590 		    "st_ioctl : EIO : MTBSR : can't set density or wfm");
13591 		return (EIO);
13592 	}
13593 
13594 	num = -num;
13595 	return (st_space_records(un, num));
13596 }
13597 
13598 static int
13599 st_mtfsfm_ioctl(struct scsi_tape *un, int cnt)
13600 {
13601 	int rval;
13602 
13603 	ST_FUNC(ST_DEVINFO, st_mtfsfm_ioctl);
13604 
13605 	rval = st_cmd(un->un_dev, SCMD_SPACE, SPACE(SP_SQFLM, cnt), SYNC_CMD);
13606 	if (rval == 0) {
13607 		un->un_pos.pmode = logical;
13608 	} else if ((un->un_status == KEY_ILLEGAL_REQUEST) &&
13609 	    (un->un_sd->sd_sense->es_add_code == 0x24)) {
13610 		/*
13611 		 * Drive says invalid field in cdb.
13612 		 * Doesn't like space multiple. Position isn't lost.
13613 		 */
13614 		un->un_err_resid = cnt;
13615 		un->un_status = 0;
13616 		rval = ENOTTY;
13617 	} else {
13618 		un->un_err_resid = cnt;
13619 		un->un_pos.pmode = invalid;
13620 	}
13621 	return (rval);
13622 }
13623 
13624 static int
13625 st_mtbsfm_ioctl(struct scsi_tape *un, int cnt)
13626 {
13627 	int rval;
13628 
13629 	ST_FUNC(ST_DEVINFO, st_mtbsfm_ioctl);
13630 
13631 	rval = st_cmd(un->un_dev, SCMD_SPACE, SPACE(SP_SQFLM, -cnt), SYNC_CMD);
13632 	if (rval == 0) {
13633 		un->un_pos.pmode = logical;
13634 	} else if ((un->un_status == KEY_ILLEGAL_REQUEST) &&
13635 	    (un->un_sd->sd_sense->es_add_code == 0x24)) {
13636 		/*
13637 		 * Drive says invalid field in cdb.
13638 		 * Doesn't like space multiple. Position isn't lost.
13639 		 */
13640 		un->un_err_resid = cnt;
13641 		un->un_status = 0;
13642 		rval = ENOTTY;
13643 	} else {
13644 		un->un_err_resid = cnt;
13645 		un->un_pos.pmode = invalid;
13646 	}
13647 	return (rval);
13648 }
13649 
13650 #if defined(__i386) || defined(__amd64)
13651 
13652 /*
13653  * release contig_mem and wake up waiting thread, if any
13654  */
13655 static void
13656 st_release_contig_mem(struct scsi_tape *un, struct contig_mem *cp)
13657 {
13658 	mutex_enter(ST_MUTEX);
13659 
13660 	ST_FUNC(ST_DEVINFO, st_release_contig_mem);
13661 
13662 	cp->cm_next = un->un_contig_mem;
13663 	un->un_contig_mem = cp;
13664 	un->un_contig_mem_available_num++;
13665 	cv_broadcast(&un->un_contig_mem_cv);
13666 
13667 	mutex_exit(ST_MUTEX);
13668 }
13669 
13670 /*
13671  * St_get_contig_mem will return a contig_mem if there is one available
13672  * in current system. Otherwise, it will try to alloc one, if the total
13673  * number of contig_mem is within st_max_contig_mem_num.
13674  * It will sleep, if allowed by caller or return NULL, if no contig_mem
13675  * is available for now.
13676  */
13677 static struct contig_mem *
13678 st_get_contig_mem(struct scsi_tape *un, size_t len, int alloc_flags)
13679 {
13680 	size_t rlen;
13681 	struct contig_mem *cp = NULL;
13682 	ddi_acc_handle_t acc_hdl;
13683 	caddr_t addr;
13684 	int big_enough = 0;
13685 	int (*dma_alloc_cb)() = (alloc_flags == KM_SLEEP) ?
13686 	    DDI_DMA_SLEEP : DDI_DMA_DONTWAIT;
13687 
13688 	/* Try to get one available contig_mem */
13689 	mutex_enter(ST_MUTEX);
13690 
13691 	ST_FUNC(ST_DEVINFO, st_get_contig_mem);
13692 
13693 	if (un->un_contig_mem_available_num > 0) {
13694 		ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough);
13695 	} else if (un->un_contig_mem_total_num < st_max_contig_mem_num) {
13696 		/*
13697 		 * we failed to get one. we're going to
13698 		 * alloc one more contig_mem for this I/O
13699 		 */
13700 		mutex_exit(ST_MUTEX);
13701 		cp = (struct contig_mem *)kmem_zalloc(
13702 		    sizeof (struct contig_mem) + biosize(),
13703 		    alloc_flags);
13704 		if (cp == NULL) {
13705 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13706 			    "alloc contig_mem failure\n");
13707 			return (NULL); /* cannot get one */
13708 		}
13709 		cp->cm_bp = (struct buf *)
13710 		    (((caddr_t)cp) + sizeof (struct contig_mem));
13711 		bioinit(cp->cm_bp);
13712 		mutex_enter(ST_MUTEX);
13713 		un->un_contig_mem_total_num++; /* one more available */
13714 	} else {
13715 		/*
13716 		 * we failed to get one and we're NOT allowed to
13717 		 * alloc more contig_mem
13718 		 */
13719 		if (alloc_flags == KM_SLEEP) {
13720 			while (un->un_contig_mem_available_num <= 0) {
13721 				cv_wait(&un->un_contig_mem_cv,
13722 				    ST_MUTEX);
13723 			}
13724 			ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough);
13725 		} else {
13726 			mutex_exit(ST_MUTEX);
13727 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13728 			    "alloc contig_mem failure\n");
13729 			return (NULL); /* cannot get one */
13730 		}
13731 	}
13732 	mutex_exit(ST_MUTEX);
13733 
13734 	/* We need to check if this block of mem is big enough for this I/O */
13735 	if (cp->cm_len < len) {
13736 		/* not big enough, need to alloc a new one */
13737 		if (ddi_dma_mem_alloc(un->un_contig_mem_hdl, len, &st_acc_attr,
13738 		    DDI_DMA_STREAMING, dma_alloc_cb, NULL,
13739 		    &addr, &rlen, &acc_hdl) != DDI_SUCCESS) {
13740 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13741 			    "alloc contig_mem failure: not enough mem\n");
13742 			st_release_contig_mem(un, cp);
13743 			cp = NULL;
13744 		} else {
13745 			if (cp->cm_addr) {
13746 				/* release previous one before attach new one */
13747 				ddi_dma_mem_free(&cp->cm_acc_hdl);
13748 			}
13749 			mutex_enter(ST_MUTEX);
13750 			un->un_max_contig_mem_len =
13751 			    un->un_max_contig_mem_len >= len ?
13752 			    un->un_max_contig_mem_len : len;
13753 			mutex_exit(ST_MUTEX);
13754 
13755 			/* attach new mem to this cp */
13756 			cp->cm_addr = addr;
13757 			cp->cm_acc_hdl = acc_hdl;
13758 			cp->cm_len = len;
13759 
13760 			goto alloc_ok; /* get one usable cp */
13761 		}
13762 	} else {
13763 		goto alloc_ok; /* get one usable cp */
13764 	}
13765 
13766 	/* cannot find/alloc a usable cp, when we get here */
13767 
13768 	mutex_enter(ST_MUTEX);
13769 	if ((un->un_max_contig_mem_len < len) ||
13770 	    (alloc_flags != KM_SLEEP)) {
13771 		mutex_exit(ST_MUTEX);
13772 		return (NULL);
13773 	}
13774 
13775 	/*
13776 	 * we're allowed to sleep, and there is one big enough
13777 	 * contig mem in the system, which is currently in use,
13778 	 * wait for it...
13779 	 */
13780 	big_enough = 1;
13781 	do {
13782 		cv_wait(&un->un_contig_mem_cv, ST_MUTEX);
13783 		ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough);
13784 	} while (cp == NULL);
13785 	mutex_exit(ST_MUTEX);
13786 
13787 	/* we get the big enough contig mem, finally */
13788 
13789 alloc_ok:
13790 	/* init bp attached to this cp */
13791 	bioreset(cp->cm_bp);
13792 	cp->cm_bp->b_un.b_addr = cp->cm_addr;
13793 	cp->cm_bp->b_private = (void *)cp;
13794 
13795 	return (cp);
13796 }
13797 
13798 /*
13799  * this is the biodone func for the bp used in big block I/O
13800  */
13801 static int
13802 st_bigblk_xfer_done(struct buf *bp)
13803 {
13804 	struct contig_mem *cp;
13805 	struct buf *orig_bp;
13806 	int remapped = 0;
13807 	int ioerr;
13808 	struct scsi_tape *un;
13809 
13810 	/* sanity check */
13811 	if (bp == NULL) {
13812 		return (DDI_FAILURE);
13813 	}
13814 
13815 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
13816 	if (un == NULL) {
13817 		return (DDI_FAILURE);
13818 	}
13819 
13820 	ST_FUNC(ST_DEVINFO, st_bigblk_xfer_done);
13821 
13822 	cp = (struct contig_mem *)bp->b_private;
13823 	orig_bp = cp->cm_bp; /* get back the bp we have replaced */
13824 	cp->cm_bp = bp;
13825 
13826 	/* special handling for special I/O */
13827 	if (cp->cm_use_sbuf) {
13828 #ifndef __lock_lint
13829 		ASSERT(un->un_sbuf_busy);
13830 #endif
13831 		un->un_sbufp = orig_bp;
13832 		cp->cm_use_sbuf = 0;
13833 	}
13834 
13835 	orig_bp->b_resid = bp->b_resid;
13836 	ioerr = geterror(bp);
13837 	if (ioerr != 0) {
13838 		bioerror(orig_bp, ioerr);
13839 	} else if (orig_bp->b_flags & B_READ) {
13840 		/* copy data back to original bp */
13841 		if (orig_bp->b_flags & (B_PHYS | B_PAGEIO)) {
13842 			bp_mapin(orig_bp);
13843 			remapped = 1;
13844 		}
13845 		bcopy(bp->b_un.b_addr, orig_bp->b_un.b_addr,
13846 		    bp->b_bcount - bp->b_resid);
13847 		if (remapped)
13848 			bp_mapout(orig_bp);
13849 	}
13850 
13851 	st_release_contig_mem(un, cp);
13852 
13853 	biodone(orig_bp);
13854 
13855 	return (DDI_SUCCESS);
13856 }
13857 
13858 /*
13859  * We use this func to replace original bp that may not be able to do I/O
13860  * in big block size with one that can
13861  */
13862 static struct buf *
13863 st_get_bigblk_bp(struct buf *bp)
13864 {
13865 	struct contig_mem *cp;
13866 	struct scsi_tape *un;
13867 	struct buf *cont_bp;
13868 	int remapped = 0;
13869 
13870 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
13871 	if (un == NULL) {
13872 		return (bp);
13873 	}
13874 
13875 	ST_FUNC(ST_DEVINFO, st_get_bigblk_bp);
13876 
13877 	/* try to get one contig_mem */
13878 	cp = st_get_contig_mem(un, bp->b_bcount, KM_SLEEP);
13879 	if (!cp) {
13880 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
13881 		    "Cannot alloc contig buf for I/O for %lu blk size",
13882 		    bp->b_bcount);
13883 		return (bp);
13884 	}
13885 	cont_bp = cp->cm_bp;
13886 	cp->cm_bp = bp;
13887 
13888 	/* make sure that we "are" using un_sbufp for special I/O */
13889 	if (bp == un->un_sbufp) {
13890 #ifndef __lock_lint
13891 		ASSERT(un->un_sbuf_busy);
13892 #endif
13893 		un->un_sbufp = cont_bp;
13894 		cp->cm_use_sbuf = 1;
13895 	}
13896 
13897 	/* clone bp */
13898 	cont_bp->b_bcount = bp->b_bcount;
13899 	cont_bp->b_resid = bp->b_resid;
13900 	cont_bp->b_iodone = st_bigblk_xfer_done;
13901 	cont_bp->b_file = bp->b_file;
13902 	cont_bp->b_offset = bp->b_offset;
13903 	cont_bp->b_dip = bp->b_dip;
13904 	cont_bp->b_error = 0;
13905 	cont_bp->b_proc = NULL;
13906 	cont_bp->b_flags = bp->b_flags & ~(B_PAGEIO | B_PHYS | B_SHADOW);
13907 	cont_bp->b_shadow = NULL;
13908 	cont_bp->b_pages = NULL;
13909 	cont_bp->b_edev = bp->b_edev;
13910 	cont_bp->b_dev = bp->b_dev;
13911 	cont_bp->b_lblkno = bp->b_lblkno;
13912 	cont_bp->b_forw = bp->b_forw;
13913 	cont_bp->b_back = bp->b_back;
13914 	cont_bp->av_forw = bp->av_forw;
13915 	cont_bp->av_back = bp->av_back;
13916 	cont_bp->b_bufsize = bp->b_bufsize;
13917 
13918 	/* get data in original bp */
13919 	if (bp->b_flags & B_WRITE) {
13920 		if (bp->b_flags & (B_PHYS | B_PAGEIO)) {
13921 			bp_mapin(bp);
13922 			remapped = 1;
13923 		}
13924 		bcopy(bp->b_un.b_addr, cont_bp->b_un.b_addr, bp->b_bcount);
13925 		if (remapped)
13926 			bp_mapout(bp);
13927 	}
13928 
13929 	return (cont_bp);
13930 }
13931 #else
13932 #ifdef __lock_lint
13933 static int
13934 st_bigblk_xfer_done(struct buf *bp)
13935 {
13936 	return (0);
13937 }
13938 #endif
13939 #endif
13940 
13941 static const char *eof_status[] =
13942 {
13943 	"NO_EOF",
13944 	"EOF_PENDING",
13945 	"EOF",
13946 	"EOT_PENDING",
13947 	"EOT",
13948 	"EOM",
13949 	"AFTER_EOM"
13950 };
13951 static const char *mode[] = {
13952 	"invalid",
13953 	"legacy",
13954 	"logical"
13955 };
13956 
13957 static void
13958 st_print_position(struct scsi_tape *un, const char *comment, tapepos_t *pos)
13959 {
13960 	ST_FUNC(ST_DEVINFO, st_print_position);
13961 	scsi_log(ST_DEVINFO, st_label, CE_NOTE,
13962 	    "%s Position data:\n", comment);
13963 	scsi_log(ST_DEVINFO, st_label, CE_CONT,
13964 	    "Positioning mode = %s", mode[pos->pmode]);
13965 	scsi_log(ST_DEVINFO, st_label, CE_CONT,
13966 	    "End Of File/Tape = %s", eof_status[pos->eof]);
13967 	scsi_log(ST_DEVINFO, st_label, CE_CONT,
13968 	    "File Number      = 0x%x", pos->fileno);
13969 	scsi_log(ST_DEVINFO, st_label, CE_CONT,
13970 	    "Block Number     = 0x%x", pos->blkno);
13971 	scsi_log(ST_DEVINFO, st_label, CE_CONT,
13972 	    "Logical Block    = 0x%"PRIx64, pos->lgclblkno);
13973 	scsi_log(ST_DEVINFO, st_label, CE_CONT,
13974 	    "Partition Number = 0x%x", pos->partition);
13975 }
13976