xref: /illumos-gate/usr/src/uts/common/io/scsi/targets/st.c (revision d79c609e2f0d1478b411b6c6b8a841f65804cfc8)
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 != NULL) &&
5365 	    (uscmd->uscsi_cdb[0] == SCMD_SPACE) &&
5366 	    (un->un_pos.pmode != invalid)) {
5367 		uchar_t status = un->un_status;
5368 		(void) st_update_block_pos(un);
5369 		un->un_status = status;
5370 	}
5371 	cv_signal(&un->un_sbuf_cv);
5372 	mutex_exit(ST_MUTEX);
5373 	(void) scsi_uscsi_copyout_and_free((intptr_t)ucmd, uscmd);
5374 	mutex_enter(ST_MUTEX);
5375 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
5376 	    "st_ioctl_cmd returns 0x%x\n", err);
5377 
5378 exit:
5379 	/* don't lose offline state */
5380 	if (offline_state) {
5381 		un->un_state = ST_STATE_OFFLINE;
5382 	}
5383 
5384 	ASSERT(mutex_owned(ST_MUTEX));
5385 	return (err);
5386 }
5387 
5388 static int
5389 st_write_fm(dev_t dev, int wfm)
5390 {
5391 	int i;
5392 	int rval;
5393 
5394 	GET_SOFT_STATE(dev);
5395 
5396 	ST_FUNC(ST_DEVINFO, st_write_fm);
5397 
5398 	ASSERT(mutex_owned(ST_MUTEX));
5399 
5400 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5401 	    "st_write_fm(dev = 0x%lx, wfm = %d)\n", dev, wfm);
5402 
5403 	/*
5404 	 * write one filemark at the time after EOT
5405 	 */
5406 	if (un->un_pos.eof >= ST_EOT) {
5407 		for (i = 0; i < wfm; i++) {
5408 			rval = st_cmd(dev, SCMD_WRITE_FILE_MARK, 1, SYNC_CMD);
5409 			if (rval == EACCES) {
5410 				return (rval);
5411 			}
5412 			if (rval != 0) {
5413 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5414 				    "st_write_fm : EIO : write EOT file mark");
5415 				return (EIO);
5416 			}
5417 		}
5418 	} else {
5419 		rval = st_cmd(dev, SCMD_WRITE_FILE_MARK, wfm, SYNC_CMD);
5420 		if (rval == EACCES) {
5421 			return (rval);
5422 		}
5423 		if (rval) {
5424 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5425 			    "st_write_fm : EIO : write file mark");
5426 			return (EIO);
5427 		}
5428 	}
5429 
5430 	ASSERT(mutex_owned(ST_MUTEX));
5431 	return (0);
5432 }
5433 
5434 #ifdef STDEBUG
5435 static void
5436 start_dump(struct scsi_tape *un, struct buf *bp)
5437 {
5438 	struct scsi_pkt *pkt = BP_PKT(bp);
5439 	uchar_t *cdbp = (uchar_t *)pkt->pkt_cdbp;
5440 
5441 	ST_FUNC(ST_DEVINFO, start_dump);
5442 
5443 	if ((st_debug & 0xf) < 6)
5444 		return;
5445 	scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
5446 	    "st_start: cmd=0x%p count=%ld resid=%ld flags=0x%x pkt=0x%p\n",
5447 	    (void *)bp->b_forw, bp->b_bcount,
5448 	    bp->b_resid, bp->b_flags, (void *)BP_PKT(bp));
5449 
5450 	st_print_cdb(ST_DEVINFO, st_label, SCSI_DEBUG,
5451 	    "st_start: cdb",  (caddr_t)cdbp);
5452 	scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
5453 	    "st_start: fileno=%d, blk=%d\n",
5454 	    un->un_pos.fileno, un->un_pos.blkno);
5455 }
5456 #endif
5457 
5458 
5459 /*
5460  * Command start && done functions
5461  */
5462 
5463 /*
5464  * st_start()
5465  *
5466  * Called from:
5467  *  st_strategy() to start a command.
5468  *  st_runout() to retry when scsi_pkt allocation fails on previous attempt(s).
5469  *  st_attach() when resuming from power down state.
5470  *  st_start_restart() to retry transport when device was previously busy.
5471  *  st_done_and_mutex_exit() to start the next command when previous is done.
5472  *
5473  * On entry:
5474  *  scsi_pkt may or may not be allocated.
5475  *
5476  */
5477 static void
5478 st_start(struct scsi_tape *un)
5479 {
5480 	struct buf *bp;
5481 	int status;
5482 
5483 	ST_FUNC(ST_DEVINFO, st_start);
5484 	ASSERT(mutex_owned(ST_MUTEX));
5485 
5486 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5487 	    "st_start(): dev = 0x%lx\n", un->un_dev);
5488 
5489 	if ((bp = un->un_quef) == NULL) {
5490 		return;
5491 	}
5492 
5493 	ASSERT((bp->b_flags & B_DONE) == 0);
5494 
5495 	/*
5496 	 * Don't send more than un_throttle commands to the HBA
5497 	 */
5498 	if ((un->un_throttle <= 0) || (un->un_ncmds >= un->un_throttle)) {
5499 		return;
5500 	}
5501 
5502 	/*
5503 	 * If the buf has no scsi_pkt call st_make_cmd() to get one and
5504 	 * build the command.
5505 	 */
5506 	if (BP_PKT(bp) == NULL) {
5507 		ASSERT((bp->b_flags & B_DONE) == 0);
5508 		st_make_cmd(un, bp, st_runout);
5509 		ASSERT((bp->b_flags & B_DONE) == 0);
5510 		status = geterror(bp);
5511 
5512 		/*
5513 		 * Some HBA's don't call bioerror() to set an error.
5514 		 * And geterror() returns zero if B_ERROR is not set.
5515 		 * So if we get zero we must check b_error.
5516 		 */
5517 		if (status == 0 && bp->b_error != 0) {
5518 			status = bp->b_error;
5519 			bioerror(bp, status);
5520 		}
5521 
5522 		/*
5523 		 * Some HBA's convert DDI_DMA_NORESOURCES into ENOMEM.
5524 		 * In tape ENOMEM has special meaning so we'll change it.
5525 		 */
5526 		if (status == ENOMEM) {
5527 			status = 0;
5528 			bioerror(bp, status);
5529 		}
5530 
5531 		/*
5532 		 * Did it fail and is it retryable?
5533 		 * If so return and wait for the callback through st_runout.
5534 		 * Also looks like scsi_init_pkt() will setup a callback even
5535 		 * if it isn't retryable.
5536 		 */
5537 		if (BP_PKT(bp) == NULL) {
5538 			if (status == 0) {
5539 				/*
5540 				 * If first attempt save state.
5541 				 */
5542 				if (un->un_state != ST_STATE_RESOURCE_WAIT) {
5543 					un->un_laststate = un->un_state;
5544 					un->un_state = ST_STATE_RESOURCE_WAIT;
5545 				}
5546 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5547 				    "temp no resources for pkt\n");
5548 			} else {
5549 				/*
5550 				 * Unlikely that it would be retryable then not.
5551 				 */
5552 				if (un->un_state == ST_STATE_RESOURCE_WAIT) {
5553 					un->un_state = un->un_laststate;
5554 				}
5555 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
5556 				    "perm no resources for pkt errno = 0x%x\n",
5557 				    status);
5558 			}
5559 			return;
5560 		}
5561 		/*
5562 		 * Worked this time set the state back.
5563 		 */
5564 		if (un->un_state == ST_STATE_RESOURCE_WAIT) {
5565 			un->un_state = un->un_laststate;
5566 		}
5567 	}
5568 
5569 	/*
5570 	 * move from waitq to runq
5571 	 */
5572 	un->un_quef = bp->b_actf;
5573 	if (un->un_quel == bp) {
5574 		/*
5575 		 *  For the case of queue having one
5576 		 *  element, set the tail pointer to
5577 		 *  point to the element.
5578 		 */
5579 		un->un_quel = bp->b_actf;
5580 	}
5581 
5582 	bp->b_actf = NULL;
5583 
5584 	if (un->un_runqf) {
5585 		un->un_runql->b_actf = bp;
5586 	} else {
5587 		un->un_runqf = bp;
5588 	}
5589 	un->un_runql = bp;
5590 
5591 
5592 	ST_CDB(ST_DEVINFO, "Start CDB", (char *)BP_PKT(bp)->pkt_cdbp);
5593 
5594 #ifdef STDEBUG
5595 	start_dump(un, bp);
5596 #endif
5597 
5598 	/* could not get here if throttle was zero */
5599 	un->un_last_throttle = un->un_throttle;
5600 	un->un_throttle = 0;	/* so nothing else will come in here */
5601 	un->un_ncmds++;
5602 
5603 	ST_DO_KSTATS(bp, kstat_waitq_to_runq);
5604 
5605 	mutex_exit(ST_MUTEX);
5606 
5607 	status = scsi_transport(BP_PKT(bp));
5608 
5609 	mutex_enter(ST_MUTEX);
5610 
5611 	if (un->un_last_throttle) {
5612 		un->un_throttle = un->un_last_throttle;
5613 	}
5614 
5615 	if (status != TRAN_ACCEPT) {
5616 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
5617 		mutex_exit(ST_MUTEX);
5618 
5619 		if (status == TRAN_BUSY) {
5620 			/* if too many retries, fail the transport */
5621 			if (st_handle_start_busy(un, bp,
5622 			    ST_TRAN_BUSY_TIMEOUT) == 0)
5623 				goto done;
5624 		}
5625 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
5626 		    "transport rejected\n");
5627 		bp->b_resid = bp->b_bcount;
5628 
5629 
5630 #ifndef __lock_lint
5631 		/*
5632 		 * warlock doesn't understand this potential
5633 		 * recursion?
5634 		 */
5635 		mutex_enter(ST_MUTEX);
5636 		ST_DO_KSTATS(bp, kstat_waitq_exit);
5637 		ST_DO_ERRSTATS(un, st_transerrs);
5638 		st_bioerror(bp, EIO);
5639 		SET_PE_FLAG(un);
5640 		st_done_and_mutex_exit(un, bp);
5641 #endif
5642 	} else {
5643 		un->un_tran_retry_ct = 0;
5644 		mutex_exit(ST_MUTEX);
5645 	}
5646 
5647 done:
5648 
5649 	mutex_enter(ST_MUTEX);
5650 }
5651 
5652 /*
5653  * if the transport is busy, then put this bp back on the waitq
5654  */
5655 static int
5656 st_handle_start_busy(struct scsi_tape *un, struct buf *bp,
5657     clock_t timeout_interval)
5658 {
5659 	struct buf *last_quef, *runq_bp;
5660 	int rval = 0;
5661 
5662 	ST_FUNC(ST_DEVINFO, st_handle_start_busy);
5663 
5664 	mutex_enter(ST_MUTEX);
5665 
5666 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5667 	    "st_handle_start_busy()\n");
5668 
5669 	/*
5670 	 * Check to see if we hit the retry timeout and one last check for
5671 	 * making sure this is the last on the runq, if it is not, we have
5672 	 * to fail
5673 	 */
5674 	if (((int)un->un_tran_retry_ct++ > st_retry_count) ||
5675 	    (un->un_runql != bp)) {
5676 		rval = -1;
5677 		goto exit;
5678 	}
5679 
5680 	/* put the bp back on the waitq */
5681 	if (un->un_quef) {
5682 		last_quef = un->un_quef;
5683 		un->un_quef = bp;
5684 		bp->b_actf = last_quef;
5685 	} else  {
5686 		bp->b_actf = NULL;
5687 		un->un_quef = bp;
5688 		un->un_quel = bp;
5689 	}
5690 
5691 	/*
5692 	 * Decrement un_ncmds so that this
5693 	 * gets thru' st_start() again.
5694 	 */
5695 	un->un_ncmds--;
5696 
5697 	/*
5698 	 * since this is an error case, we won't have to do
5699 	 * this list walking much.  We've already made sure this bp was the
5700 	 * last on the runq
5701 	 */
5702 	runq_bp = un->un_runqf;
5703 
5704 	if (un->un_runqf == bp) {
5705 		un->un_runqf = NULL;
5706 		un->un_runql = NULL;
5707 	} else {
5708 		while (runq_bp) {
5709 			if (runq_bp->b_actf == bp) {
5710 				runq_bp->b_actf = NULL;
5711 				un->un_runql = runq_bp;
5712 				break;
5713 			}
5714 			runq_bp = runq_bp->b_actf;
5715 		}
5716 	}
5717 
5718 
5719 	/*
5720 	 * send a marker pkt, if appropriate
5721 	 */
5722 	st_hba_unflush(un);
5723 
5724 	/*
5725 	 * all queues are aligned, we are just waiting to
5726 	 * transport, don't alloc any more buf p's, when
5727 	 * st_start is reentered.
5728 	 */
5729 	(void) timeout(st_start_restart, un, timeout_interval);
5730 
5731 exit:
5732 	mutex_exit(ST_MUTEX);
5733 	return (rval);
5734 }
5735 
5736 
5737 /*
5738  * st_runout a callback that is called what a resource allocatation failed
5739  */
5740 static int
5741 st_runout(caddr_t arg)
5742 {
5743 	struct scsi_tape *un = (struct scsi_tape *)arg;
5744 	struct buf *bp;
5745 	ASSERT(un != NULL);
5746 
5747 	ST_FUNC(ST_DEVINFO, st_runout);
5748 
5749 	mutex_enter(ST_MUTEX);
5750 
5751 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_runout()\n");
5752 
5753 	bp = un->un_quef;
5754 
5755 	/*
5756 	 * failed scsi_init_pkt(). If errno is zero its retryable.
5757 	 */
5758 	if ((bp != NULL) && (geterror(bp) != 0)) {
5759 
5760 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
5761 		    "errors after pkt alloc (b_flags=0x%x, b_error=0x%x)\n",
5762 		    bp->b_flags, geterror(bp));
5763 		ASSERT((bp->b_flags & B_DONE) == 0);
5764 
5765 		un->un_quef = bp->b_actf;
5766 		if (un->un_quel == bp) {
5767 			/*
5768 			 *  For the case of queue having one
5769 			 *  element, set the tail pointer to
5770 			 *  point to the element.
5771 			 */
5772 			un->un_quel = bp->b_actf;
5773 		}
5774 		mutex_exit(ST_MUTEX);
5775 		bp->b_actf = NULL;
5776 
5777 		ASSERT((bp->b_flags & B_DONE) == 0);
5778 
5779 		/*
5780 		 * Set resid, Error already set, then unblock calling thread.
5781 		 */
5782 		bp->b_resid = bp->b_bcount;
5783 		biodone(bp);
5784 	} else {
5785 		/*
5786 		 * Try Again
5787 		 */
5788 		st_start(un);
5789 		mutex_exit(ST_MUTEX);
5790 	}
5791 
5792 	/*
5793 	 * Comments courtesy of sd.c
5794 	 * The scsi_init_pkt routine allows for the callback function to
5795 	 * return a 0 indicating the callback should be rescheduled or a 1
5796 	 * indicating not to reschedule. This routine always returns 1
5797 	 * because the driver always provides a callback function to
5798 	 * scsi_init_pkt. This results in a callback always being scheduled
5799 	 * (via the scsi_init_pkt callback implementation) if a resource
5800 	 * failure occurs.
5801 	 */
5802 
5803 	return (1);
5804 }
5805 
5806 /*
5807  * st_done_and_mutex_exit()
5808  *	- remove bp from runq
5809  *	- start up the next request
5810  *	- if this was an asynch bp, clean up
5811  *	- exit with released mutex
5812  */
5813 static void
5814 st_done_and_mutex_exit(struct scsi_tape *un, struct buf *bp)
5815 {
5816 	struct buf *runqbp, *prevbp;
5817 	int	pe_flagged = 0;
5818 
5819 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
5820 #if !defined(lint)
5821 	_NOTE(LOCK_RELEASED_AS_SIDE_EFFECT(&un->un_sd->sd_mutex))
5822 #endif
5823 
5824 	ST_FUNC(ST_DEVINFO, st_done_and_mutex_exit);
5825 
5826 	ASSERT(mutex_owned(ST_MUTEX));
5827 
5828 	/*
5829 	 * if bp is still on the runq (anywhere), then remove it
5830 	 */
5831 	prevbp = NULL;
5832 	for (runqbp = un->un_runqf; runqbp != 0; runqbp = runqbp->b_actf) {
5833 		if (runqbp == bp) {
5834 			if (runqbp == un->un_runqf) {
5835 				un->un_runqf = bp->b_actf;
5836 			} else {
5837 				prevbp->b_actf = bp->b_actf;
5838 			}
5839 			if (un->un_runql == bp) {
5840 				un->un_runql = prevbp;
5841 			}
5842 			break;
5843 		}
5844 		prevbp = runqbp;
5845 	}
5846 	bp->b_actf = NULL;
5847 
5848 	un->un_ncmds--;
5849 	cv_signal(&un->un_queue_cv);
5850 
5851 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5852 	    "st_done_and_mutex_exit(): cmd=0x%x count=%ld resid=%ld  flags="
5853 	    "0x%x\n", (uchar_t)*((caddr_t)(BP_PKT(bp))->pkt_cdbp), bp->b_bcount,
5854 	    bp->b_resid, bp->b_flags);
5855 
5856 
5857 	/*
5858 	 * update kstats with transfer count info
5859 	 */
5860 	if (un->un_stats && (bp != un->un_sbufp) && IS_RW(bp)) {
5861 		uint32_t n_done =  bp->b_bcount - bp->b_resid;
5862 		if (bp->b_flags & B_READ) {
5863 			IOSP->reads++;
5864 			IOSP->nread += n_done;
5865 		} else {
5866 			IOSP->writes++;
5867 			IOSP->nwritten += n_done;
5868 		}
5869 	}
5870 
5871 	/*
5872 	 * Start the next one before releasing resources on this one, if
5873 	 * there is something on the queue and persistent errors has not been
5874 	 * flagged
5875 	 */
5876 
5877 	if ((pe_flagged = IS_PE_FLAG_SET(un)) != 0) {
5878 		un->un_last_resid = bp->b_resid;
5879 		un->un_last_count = bp->b_bcount;
5880 	}
5881 
5882 	if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
5883 		cv_broadcast(&un->un_tape_busy_cv);
5884 	} else if (un->un_quef && un->un_throttle && !pe_flagged) {
5885 		st_start(un);
5886 	}
5887 
5888 	if (bp == un->un_sbufp && (bp->b_flags & B_ASYNC)) {
5889 		/*
5890 		 * Since we marked this ourselves as ASYNC,
5891 		 * there isn't anybody around waiting for
5892 		 * completion any more.
5893 		 */
5894 		uchar_t com = (uchar_t)(uintptr_t)bp->b_forw;
5895 		if (com == SCMD_READ || com == SCMD_WRITE) {
5896 			bp->b_un.b_addr = (caddr_t)0;
5897 		}
5898 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
5899 		    "st_done_and_mutex_exit(async): freeing pkt\n");
5900 		scsi_destroy_pkt(BP_PKT(bp));
5901 		un->un_sbuf_busy = 0;
5902 		cv_signal(&un->un_sbuf_cv);
5903 		mutex_exit(ST_MUTEX);
5904 		return;
5905 	}
5906 
5907 	if (bp == un->un_sbufp && BP_UCMD(bp)) {
5908 		/*
5909 		 * Copy status from scsi_pkt to uscsi_cmd
5910 		 * since st_ioctl_cmd needs it
5911 		 */
5912 		BP_UCMD(bp)->uscsi_status = SCBP_C(BP_PKT(bp));
5913 	}
5914 
5915 
5916 #ifdef STDEBUG
5917 	if (((st_debug & 0xf) >= 4) &&
5918 	    (((un->un_pos.blkno % 100) == 0) || IS_PE_FLAG_SET(un))) {
5919 
5920 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
5921 		    "st_d_a_m_exit(): ncmds = %d, thr = %d, "
5922 		    "un_errno = %d, un_pe = %d\n",
5923 		    un->un_ncmds, un->un_throttle, un->un_errno,
5924 		    un->un_persist_errors);
5925 	}
5926 
5927 #endif
5928 
5929 	mutex_exit(ST_MUTEX);
5930 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
5931 	    "st_done_and_mutex_exit: freeing pkt\n");
5932 
5933 	scsi_destroy_pkt(BP_PKT(bp));
5934 
5935 	biodone(bp);
5936 
5937 	/*
5938 	 * now that we biodoned that command, if persistent errors have been
5939 	 * flagged, flush the waitq
5940 	 */
5941 	if (pe_flagged)
5942 		st_flush(un);
5943 }
5944 
5945 
5946 /*
5947  * Tape error, flush tape driver queue.
5948  */
5949 static void
5950 st_flush(struct scsi_tape *un)
5951 {
5952 	struct buf *bp;
5953 
5954 	ST_FUNC(ST_DEVINFO, st_flush);
5955 
5956 	mutex_enter(ST_MUTEX);
5957 
5958 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
5959 	    "st_flush(), ncmds = %d, quef = 0x%p\n",
5960 	    un->un_ncmds, (void *)un->un_quef);
5961 
5962 	/*
5963 	 * if we still have commands outstanding, wait for them to come in
5964 	 * before flushing the queue, and make sure there is a queue
5965 	 */
5966 	if (un->un_ncmds || !un->un_quef)
5967 		goto exit;
5968 
5969 	/*
5970 	 * we have no more commands outstanding, so let's deal with special
5971 	 * cases in the queue for EOM and FM. If we are here, and un_errno
5972 	 * is 0, then we know there was no error and we return a 0 read or
5973 	 * write before showing errors
5974 	 */
5975 
5976 	/* Flush the wait queue. */
5977 	while ((bp = un->un_quef) != NULL) {
5978 		un->un_quef = bp->b_actf;
5979 
5980 		bp->b_resid = bp->b_bcount;
5981 
5982 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
5983 		    "st_flush() : blkno=%d, err=%d, b_bcount=%ld\n",
5984 		    un->un_pos.blkno, un->un_errno, bp->b_bcount);
5985 
5986 		st_set_pe_errno(un);
5987 
5988 		bioerror(bp, un->un_errno);
5989 
5990 		mutex_exit(ST_MUTEX);
5991 		/* it should have one, but check anyway */
5992 		if (BP_PKT(bp)) {
5993 			scsi_destroy_pkt(BP_PKT(bp));
5994 		}
5995 		biodone(bp);
5996 		mutex_enter(ST_MUTEX);
5997 	}
5998 
5999 	/*
6000 	 * It's not a bad practice to reset the
6001 	 * waitq tail pointer to NULL.
6002 	 */
6003 	un->un_quel = NULL;
6004 
6005 exit:
6006 	/* we mucked with the queue, so let others know about it */
6007 	cv_signal(&un->un_queue_cv);
6008 	mutex_exit(ST_MUTEX);
6009 }
6010 
6011 
6012 /*
6013  * Utility functions
6014  */
6015 static int
6016 st_determine_generic(dev_t dev)
6017 {
6018 	int bsize;
6019 	static char *cart = "0.25 inch cartridge";
6020 	char *sizestr;
6021 
6022 	GET_SOFT_STATE(dev);
6023 
6024 	ST_FUNC(ST_DEVINFO, st_determine_generic);
6025 
6026 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6027 	    "st_determine_generic(dev = 0x%lx)\n", dev);
6028 
6029 	ASSERT(mutex_owned(ST_MUTEX));
6030 
6031 	if (st_modesense(un)) {
6032 		return (-1);
6033 	}
6034 
6035 	bsize = (un->un_mspl->high_bl << 16)	|
6036 	    (un->un_mspl->mid_bl << 8)	|
6037 	    (un->un_mspl->low_bl);
6038 
6039 	if (bsize == 0) {
6040 		un->un_dp->options |= ST_VARIABLE;
6041 		un->un_dp->bsize = 0;
6042 		un->un_bsize = 0;
6043 	} else if (bsize > ST_MAXRECSIZE_FIXED) {
6044 		/*
6045 		 * record size of this device too big.
6046 		 * try and convert it to variable record length.
6047 		 *
6048 		 */
6049 		un->un_dp->options |= ST_VARIABLE;
6050 		if (st_change_block_size(dev, 0) != 0) {
6051 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
6052 			    "Fixed Record Size %d is too large\n", bsize);
6053 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
6054 			    "Cannot switch to variable record size\n");
6055 			un->un_dp->options &= ~ST_VARIABLE;
6056 			return (-1);
6057 		}
6058 	} else if (st_change_block_size(dev, 0) == 0) {
6059 		/*
6060 		 * If the drive was set to a non zero block size,
6061 		 * See if it can be set to a zero block size.
6062 		 * If it works, ST_VARIABLE so user can set it as they want.
6063 		 */
6064 		un->un_dp->options |= ST_VARIABLE;
6065 		un->un_dp->bsize = 0;
6066 		un->un_bsize = 0;
6067 	} else {
6068 		un->un_dp->bsize = bsize;
6069 		un->un_bsize = bsize;
6070 	}
6071 
6072 
6073 	switch (un->un_mspl->density) {
6074 	default:
6075 	case 0x0:
6076 		/*
6077 		 * default density, cannot determine any other
6078 		 * information.
6079 		 */
6080 		sizestr = "Unknown type- assuming 0.25 inch cartridge";
6081 		un->un_dp->type = ST_TYPE_DEFAULT;
6082 		un->un_dp->options |= (ST_AUTODEN_OVERRIDE|ST_QIC);
6083 		break;
6084 	case 0x1:
6085 	case 0x2:
6086 	case 0x3:
6087 	case 0x6:
6088 		/*
6089 		 * 1/2" reel
6090 		 */
6091 		sizestr = "0.50 inch reel";
6092 		un->un_dp->type = ST_TYPE_REEL;
6093 		un->un_dp->options |= ST_REEL;
6094 		un->un_dp->densities[0] = 0x1;
6095 		un->un_dp->densities[1] = 0x2;
6096 		un->un_dp->densities[2] = 0x6;
6097 		un->un_dp->densities[3] = 0x3;
6098 		break;
6099 	case 0x4:
6100 	case 0x5:
6101 	case 0x7:
6102 	case 0x0b:
6103 
6104 		/*
6105 		 * Quarter inch.
6106 		 */
6107 		sizestr = cart;
6108 		un->un_dp->type = ST_TYPE_DEFAULT;
6109 		un->un_dp->options |= ST_QIC;
6110 
6111 		un->un_dp->densities[1] = 0x4;
6112 		un->un_dp->densities[2] = 0x5;
6113 		un->un_dp->densities[3] = 0x7;
6114 		un->un_dp->densities[0] = 0x0b;
6115 		break;
6116 
6117 	case 0x0f:
6118 	case 0x10:
6119 	case 0x11:
6120 	case 0x12:
6121 		/*
6122 		 * QIC-120, QIC-150, QIC-320, QIC-600
6123 		 */
6124 		sizestr = cart;
6125 		un->un_dp->type = ST_TYPE_DEFAULT;
6126 		un->un_dp->options |= ST_QIC;
6127 		un->un_dp->densities[0] = 0x0f;
6128 		un->un_dp->densities[1] = 0x10;
6129 		un->un_dp->densities[2] = 0x11;
6130 		un->un_dp->densities[3] = 0x12;
6131 		break;
6132 
6133 	case 0x09:
6134 	case 0x0a:
6135 	case 0x0c:
6136 	case 0x0d:
6137 		/*
6138 		 * 1/2" cartridge tapes. Include HI-TC.
6139 		 */
6140 		sizestr = cart;
6141 		sizestr[2] = '5';
6142 		sizestr[3] = '0';
6143 		un->un_dp->type = ST_TYPE_HIC;
6144 		un->un_dp->densities[0] = 0x09;
6145 		un->un_dp->densities[1] = 0x0a;
6146 		un->un_dp->densities[2] = 0x0c;
6147 		un->un_dp->densities[3] = 0x0d;
6148 		break;
6149 
6150 	case 0x13:
6151 			/* DDS-2/DDS-3 scsi spec densities */
6152 	case 0x24:
6153 	case 0x25:
6154 	case 0x26:
6155 		sizestr = "DAT Data Storage (DDS)";
6156 		un->un_dp->type = ST_TYPE_DAT;
6157 		un->un_dp->options |= ST_AUTODEN_OVERRIDE;
6158 		break;
6159 
6160 	case 0x14:
6161 		/*
6162 		 * Helical Scan (Exabyte) devices
6163 		 */
6164 		sizestr = "8mm helical scan cartridge";
6165 		un->un_dp->type = ST_TYPE_EXABYTE;
6166 		un->un_dp->options |= ST_AUTODEN_OVERRIDE;
6167 		break;
6168 	}
6169 
6170 	/*
6171 	 * Assume LONG ERASE, BSF and BSR
6172 	 */
6173 
6174 	un->un_dp->options |=
6175 	    (ST_LONG_ERASE | ST_UNLOADABLE | ST_BSF | ST_BSR | ST_KNOWS_EOD);
6176 
6177 	/*
6178 	 * Only if mode sense data says no buffered write, set NOBUF
6179 	 */
6180 	if (un->un_mspl->bufm == 0)
6181 		un->un_dp->options |= ST_NOBUF;
6182 
6183 	/*
6184 	 * set up large read and write retry counts
6185 	 */
6186 
6187 	un->un_dp->max_rretries = un->un_dp->max_wretries = 1000;
6188 
6189 	/*
6190 	 * If this is a 0.50 inch reel tape, and
6191 	 * it is *not* variable mode, try and
6192 	 * set it to variable record length
6193 	 * mode.
6194 	 */
6195 	if ((un->un_dp->options & ST_REEL) && un->un_bsize != 0 &&
6196 	    (un->un_dp->options & ST_VARIABLE)) {
6197 		if (st_change_block_size(dev, 0) == 0) {
6198 			un->un_dp->bsize = 0;
6199 			un->un_mspl->high_bl = un->un_mspl->mid_bl =
6200 			    un->un_mspl->low_bl = 0;
6201 		}
6202 	}
6203 
6204 	/*
6205 	 * Write to console about type of device found
6206 	 */
6207 	ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
6208 	    "Generic Drive, Vendor=%s\n\t%s", un->un_dp->name,
6209 	    sizestr);
6210 	if (un->un_dp->options & ST_VARIABLE) {
6211 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
6212 		    "!Variable record length I/O\n");
6213 	} else {
6214 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
6215 		    "!Fixed record length (%d byte blocks) I/O\n",
6216 		    un->un_dp->bsize);
6217 	}
6218 	ASSERT(mutex_owned(ST_MUTEX));
6219 	return (0);
6220 }
6221 
6222 static int
6223 st_determine_density(dev_t dev, int rw)
6224 {
6225 	int rval = 0;
6226 
6227 	GET_SOFT_STATE(dev);
6228 
6229 	ST_FUNC(ST_DEVINFO, st_determine_density);
6230 
6231 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6232 	    "st_determine_density(dev = 0x%lx, rw = %s)\n",
6233 	    dev, (rw == B_WRITE ? wr_str: rd_str));
6234 
6235 	ASSERT(mutex_owned(ST_MUTEX));
6236 
6237 	/*
6238 	 * If we're past BOT, density is determined already.
6239 	 */
6240 	if (un->un_pos.pmode == logical) {
6241 		if (un->un_pos.lgclblkno != 0) {
6242 			goto exit;
6243 		}
6244 	} else if (un->un_pos.pmode == legacy) {
6245 		if ((un->un_pos.fileno != 0) || (un->un_pos.blkno != 0)) {
6246 			/*
6247 			 * XXX: put in a bitch message about attempting to
6248 			 * XXX: change density past BOT.
6249 			 */
6250 			goto exit;
6251 		}
6252 	} else {
6253 		goto exit;
6254 	}
6255 
6256 
6257 	/*
6258 	 * If we're going to be writing, we set the density
6259 	 */
6260 	if (rw == 0 || rw == B_WRITE) {
6261 		/* un_curdens is used as an index into densities table */
6262 		un->un_curdens = MT_DENSITY(un->un_dev);
6263 		if (st_set_density(dev)) {
6264 			rval = -1;
6265 		}
6266 		goto exit;
6267 	}
6268 
6269 	/*
6270 	 * If density is known already,
6271 	 * we don't have to get it again.(?)
6272 	 */
6273 	if (!un->un_density_known) {
6274 		if (st_get_density(dev)) {
6275 			rval = -1;
6276 		}
6277 	}
6278 
6279 exit:
6280 	ASSERT(mutex_owned(ST_MUTEX));
6281 	return (rval);
6282 }
6283 
6284 
6285 /*
6286  * Try to determine density. We do this by attempting to read the
6287  * first record off the tape, cycling through the available density
6288  * codes as we go.
6289  */
6290 
6291 static int
6292 st_get_density(dev_t dev)
6293 {
6294 	int succes = 0, rval = -1, i;
6295 	uint_t size;
6296 	uchar_t dens, olddens;
6297 
6298 	GET_SOFT_STATE(dev);
6299 
6300 	ST_FUNC(ST_DEVINFO, st_get_density);
6301 
6302 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6303 	    "st_get_density(dev = 0x%lx)\n", dev);
6304 
6305 	ASSERT(mutex_owned(ST_MUTEX));
6306 
6307 	/*
6308 	 * If Auto Density override is enabled The drive has
6309 	 * only one density and there is no point in attempting
6310 	 * find the correct one.
6311 	 *
6312 	 * Since most modern drives auto detect the density
6313 	 * and format of the recorded media before they come
6314 	 * ready. What this function does is a legacy behavior
6315 	 * and modern drives not only don't need it, The backup
6316 	 * utilities that do positioning via uscsi find the un-
6317 	 * expected rewinds problematic.
6318 	 *
6319 	 * The drives that need this are old reel to reel devices.
6320 	 * I took a swag and said they must be scsi-1 or older.
6321 	 * I don't beleave there will any of the newer devices
6322 	 * that need this. There will be some scsi-1 devices that
6323 	 * don't need this but I don't think they will be using the
6324 	 * BIG aftermarket backup and restore utilitys.
6325 	 */
6326 	if ((un->un_dp->options & ST_AUTODEN_OVERRIDE) ||
6327 	    (un->un_sd->sd_inq->inq_ansi > 1)) {
6328 		un->un_density_known = 1;
6329 		rval = 0;
6330 		goto exit;
6331 	}
6332 
6333 	/*
6334 	 * This will only work on variable record length tapes
6335 	 * if and only if all variable record length tapes autodensity
6336 	 * select.
6337 	 */
6338 	size = (unsigned)(un->un_dp->bsize ? un->un_dp->bsize : SECSIZE);
6339 	un->un_tmpbuf = kmem_alloc(size, KM_SLEEP);
6340 
6341 	/*
6342 	 * Start at the specified density
6343 	 */
6344 
6345 	dens = olddens = un->un_curdens = MT_DENSITY(un->un_dev);
6346 
6347 	for (i = 0; i < NDENSITIES; i++, ((un->un_curdens == NDENSITIES - 1) ?
6348 	    (un->un_curdens = 0) : (un->un_curdens += 1))) {
6349 		/*
6350 		 * If we've done this density before,
6351 		 * don't bother to do it again.
6352 		 */
6353 		dens = un->un_dp->densities[un->un_curdens];
6354 		if (i > 0 && dens == olddens)
6355 			continue;
6356 		olddens = dens;
6357 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6358 		    "trying density 0x%x\n", dens);
6359 		if (st_set_density(dev)) {
6360 			continue;
6361 		}
6362 
6363 		/*
6364 		 * XXX - the creates lots of headaches and slowdowns - must
6365 		 * fix.
6366 		 */
6367 		succes = (st_cmd(dev, SCMD_READ, (int)size, SYNC_CMD) == 0);
6368 		if (st_cmd(dev, SCMD_REWIND, 0, SYNC_CMD)) {
6369 			break;
6370 		}
6371 		if (succes) {
6372 			st_init(un);
6373 			rval = 0;
6374 			un->un_density_known = 1;
6375 			break;
6376 		}
6377 	}
6378 	kmem_free(un->un_tmpbuf, size);
6379 	un->un_tmpbuf = 0;
6380 
6381 exit:
6382 	ASSERT(mutex_owned(ST_MUTEX));
6383 	return (rval);
6384 }
6385 
6386 static int
6387 st_set_density(dev_t dev)
6388 {
6389 	int rval = 0;
6390 
6391 	GET_SOFT_STATE(dev);
6392 
6393 	ST_FUNC(ST_DEVINFO, st_set_density);
6394 
6395 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6396 	    "st_set_density(dev = 0x%lx): density = 0x%x\n", dev,
6397 	    un->un_dp->densities[un->un_curdens]);
6398 
6399 	ASSERT(mutex_owned(ST_MUTEX));
6400 
6401 	un->un_mspl->density = un->un_dp->densities[un->un_curdens];
6402 
6403 	if ((un->un_dp->options & ST_AUTODEN_OVERRIDE) == 0) {
6404 		/*
6405 		 * If auto density override is not set, Use mode select
6406 		 * to set density and compression.
6407 		 */
6408 		if (st_modeselect(un)) {
6409 			rval = -1;
6410 		}
6411 	} else if ((un->un_dp->options & ST_MODE_SEL_COMP) != 0) {
6412 		/*
6413 		 * If auto density and mode select compression are set,
6414 		 * This is a drive with one density code but compression
6415 		 * can be enabled or disabled.
6416 		 * Set compression but no need to set density.
6417 		 */
6418 		rval = st_set_compression(un);
6419 		if ((rval != 0) && (rval != EALREADY)) {
6420 			rval = -1;
6421 		} else {
6422 			rval = 0;
6423 		}
6424 	}
6425 
6426 	/* If sucessful set density and/or compression, mark density known */
6427 	if (rval == 0) {
6428 		un->un_density_known = 1;
6429 	}
6430 
6431 	ASSERT(mutex_owned(ST_MUTEX));
6432 	return (rval);
6433 }
6434 
6435 static int
6436 st_loadtape(dev_t dev)
6437 {
6438 	int rval;
6439 
6440 	GET_SOFT_STATE(dev);
6441 
6442 	ST_FUNC(ST_DEVINFO, st_load_tape);
6443 
6444 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6445 	    "st_loadtape(dev = 0x%lx)\n", dev);
6446 
6447 	ASSERT(mutex_owned(ST_MUTEX));
6448 
6449 	/*
6450 	 * 'LOAD' the tape to BOT by rewinding
6451 	 */
6452 	rval = st_cmd(dev, SCMD_REWIND, 1, SYNC_CMD);
6453 	if (rval == 0) {
6454 		st_init(un);
6455 		un->un_density_known = 0;
6456 	}
6457 
6458 	ASSERT(mutex_owned(ST_MUTEX));
6459 	return (rval);
6460 }
6461 
6462 
6463 /*
6464  * Note: QIC devices aren't so smart.  If you try to append
6465  * after EOM, the write can fail because the device doesn't know
6466  * it's at EOM.	 In that case, issue a read.  The read should fail
6467  * because there's no data, but the device knows it's at EOM,
6468  * so a subsequent write should succeed.  To further confuse matters,
6469  * the target returns the same error if the tape is positioned
6470  * such that a write would overwrite existing data.  That's why
6471  * we have to do the append test.  A read in the middle of
6472  * recorded data would succeed, thus indicating we're attempting
6473  * something illegal.
6474  */
6475 
6476 
6477 static void
6478 st_test_append(struct buf *bp)
6479 {
6480 	dev_t dev = bp->b_edev;
6481 	struct scsi_tape *un;
6482 	uchar_t status;
6483 	unsigned bcount;
6484 
6485 	un = ddi_get_soft_state(st_state, MTUNIT(dev));
6486 
6487 	ST_FUNC(ST_DEVINFO, st_test_append);
6488 
6489 	ASSERT(mutex_owned(ST_MUTEX));
6490 
6491 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6492 	    "st_test_append(): fileno %d\n", un->un_pos.fileno);
6493 
6494 	un->un_laststate = un->un_state;
6495 	un->un_state = ST_STATE_APPEND_TESTING;
6496 	un->un_test_append = 0;
6497 
6498 	/*
6499 	 * first, map in the buffer, because we're doing a double write --
6500 	 * first into the kernel, then onto the tape.
6501 	 */
6502 	bp_mapin(bp);
6503 
6504 	/*
6505 	 * get a copy of the data....
6506 	 */
6507 	un->un_tmpbuf = kmem_alloc((unsigned)bp->b_bcount, KM_SLEEP);
6508 	bcopy(bp->b_un.b_addr, un->un_tmpbuf, (uint_t)bp->b_bcount);
6509 
6510 	/*
6511 	 * attempt the write..
6512 	 */
6513 
6514 	if (st_cmd(dev, (int)SCMD_WRITE, (int)bp->b_bcount, SYNC_CMD) == 0) {
6515 success:
6516 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6517 		    "append write succeeded\n");
6518 		bp->b_resid = un->un_sbufp->b_resid;
6519 		mutex_exit(ST_MUTEX);
6520 		bcount = (unsigned)bp->b_bcount;
6521 		biodone(bp);
6522 		mutex_enter(ST_MUTEX);
6523 		un->un_laststate = un->un_state;
6524 		un->un_state = ST_STATE_OPEN;
6525 		kmem_free(un->un_tmpbuf, bcount);
6526 		un->un_tmpbuf = NULL;
6527 		return;
6528 	}
6529 
6530 	/*
6531 	 * The append failed. Do a short read. If that fails,  we are at EOM
6532 	 * so we can retry the write command. If that succeeds, than we're
6533 	 * all screwed up (the controller reported a real error).
6534 	 *
6535 	 * XXX: should the dummy read be > SECSIZE? should it be the device's
6536 	 * XXX: block size?
6537 	 *
6538 	 */
6539 	status = un->un_status;
6540 	un->un_status = 0;
6541 	(void) st_cmd(dev, SCMD_READ, SECSIZE, SYNC_CMD);
6542 	if (un->un_status == KEY_BLANK_CHECK) {
6543 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6544 		    "append at EOM\n");
6545 		/*
6546 		 * Okay- the read failed. We should actually have confused
6547 		 * the controller enough to allow writing. In any case, the
6548 		 * i/o is on its own from here on out.
6549 		 */
6550 		un->un_laststate = un->un_state;
6551 		un->un_state = ST_STATE_OPEN;
6552 		bcopy(bp->b_un.b_addr, un->un_tmpbuf, (uint_t)bp->b_bcount);
6553 		if (st_cmd(dev, (int)SCMD_WRITE, (int)bp->b_bcount,
6554 		    SYNC_CMD) == 0) {
6555 			goto success;
6556 		}
6557 	}
6558 
6559 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6560 	    "append write failed- not at EOM\n");
6561 	bp->b_resid = bp->b_bcount;
6562 	st_bioerror(bp, EIO);
6563 
6564 	ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6565 	    "st_test_append : EIO : append write failed - not at EOM");
6566 
6567 	/*
6568 	 * backspace one record to get back to where we were
6569 	 */
6570 	if (st_cmd(dev, SCMD_SPACE, Blk(-1), SYNC_CMD)) {
6571 		un->un_pos.pmode = invalid;
6572 	}
6573 
6574 	un->un_err_resid = bp->b_resid;
6575 	un->un_status = status;
6576 
6577 	/*
6578 	 * Note: biodone will do a bp_mapout()
6579 	 */
6580 	mutex_exit(ST_MUTEX);
6581 	bcount = (unsigned)bp->b_bcount;
6582 	biodone(bp);
6583 	mutex_enter(ST_MUTEX);
6584 	un->un_laststate = un->un_state;
6585 	un->un_state = ST_STATE_OPEN_PENDING_IO;
6586 	kmem_free(un->un_tmpbuf, bcount);
6587 	un->un_tmpbuf = NULL;
6588 }
6589 
6590 /*
6591  * Special command handler
6592  */
6593 
6594 /*
6595  * common st_cmd code. The fourth parameter states
6596  * whether the caller wishes to await the results
6597  * Note the release of the mutex during most of the function
6598  */
6599 static int
6600 st_cmd(dev_t dev, int com, int count, int wait)
6601 {
6602 	struct buf *bp;
6603 	int err;
6604 
6605 	GET_SOFT_STATE(dev);
6606 
6607 	ST_FUNC(ST_DEVINFO, st_cmd);
6608 
6609 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6610 	    "st_cmd(dev = 0x%lx, com = 0x%x, count = %x, wait = %d)\n",
6611 	    dev, com, count, wait);
6612 
6613 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
6614 	ASSERT(mutex_owned(ST_MUTEX));
6615 
6616 #ifdef STDEBUG
6617 	if ((st_debug & 0xf)) {
6618 		st_debug_cmds(un, com, count, wait);
6619 	}
6620 #endif
6621 
6622 	/* check to see if this command requires the drive to be reserved */
6623 	err = st_check_cmd_for_need_to_reserve(un, com, count);
6624 
6625 	if (err) {
6626 		return (err);
6627 	}
6628 
6629 	while (un->un_sbuf_busy)
6630 		cv_wait(&un->un_sbuf_cv, ST_MUTEX);
6631 	un->un_sbuf_busy = 1;
6632 
6633 	bp = un->un_sbufp;
6634 	bzero(bp, sizeof (buf_t));
6635 
6636 	bp->b_flags = (wait) ? B_BUSY : B_BUSY|B_ASYNC;
6637 
6638 	/*
6639 	 * Set count to the actual size of the data tranfer.
6640 	 * For commands with no data transfer, set bp->b_bcount
6641 	 * to the value to be used when constructing the
6642 	 * cdb in st_make_cmd().
6643 	 */
6644 	switch (com) {
6645 	case SCMD_READ:
6646 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6647 		    "special read %d\n", count);
6648 		bp->b_flags |= B_READ;
6649 		bp->b_un.b_addr = un->un_tmpbuf;
6650 		break;
6651 
6652 	case SCMD_WRITE:
6653 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6654 		    "special write %d\n", count);
6655 		bp->b_un.b_addr = un->un_tmpbuf;
6656 		break;
6657 
6658 	case SCMD_WRITE_FILE_MARK:
6659 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6660 		    "write %d file marks\n", count);
6661 		bp->b_bcount = count;
6662 		count = 0;
6663 		break;
6664 
6665 	case SCMD_REWIND:
6666 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "rewind\n");
6667 		bp->b_bcount = 0;
6668 		count = 0;
6669 		break;
6670 
6671 	case SCMD_SPACE:
6672 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "space\n");
6673 		/*
6674 		 * XXX The user could have entered a number that will
6675 		 * not fit in the 12 bit count field. Whats new here
6676 		 * checking that. Down the road this should use space(16).
6677 		 */
6678 		if ((SPACE_CNT(count) > 0x7fffff) ||
6679 		    (SPACE_CNT(count) < -(0x7fffff))) {
6680 			un->un_sbuf_busy = 0;
6681 			cv_signal(&un->un_sbuf_cv);
6682 			return (EINVAL);
6683 		}
6684 		bp->b_bcount = count;
6685 		count = 0;
6686 		break;
6687 
6688 	case SCMD_RESERVE:
6689 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "reserve");
6690 		bp->b_bcount = 0;
6691 		count = 0;
6692 		break;
6693 
6694 	case SCMD_RELEASE:
6695 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "release");
6696 		bp->b_bcount = 0;
6697 		count = 0;
6698 		break;
6699 
6700 	case SCMD_LOAD:
6701 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6702 		    "%s tape\n", (count & LD_LOAD) ? "load" : "unload");
6703 		bp->b_bcount = count;
6704 		count = 0;
6705 		break;
6706 
6707 	case SCMD_ERASE:
6708 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6709 		    "erase tape\n");
6710 		bp->b_bcount = 0;
6711 		count = 0;
6712 		break;
6713 
6714 	case SCMD_MODE_SENSE:
6715 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6716 		    "mode sense\n");
6717 		bp->b_flags |= B_READ;
6718 		bp->b_un.b_addr = (caddr_t)(un->un_mspl);
6719 		break;
6720 
6721 	case SCMD_MODE_SELECT:
6722 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6723 		    "mode select\n");
6724 		bp->b_un.b_addr = (caddr_t)(un->un_mspl);
6725 		break;
6726 
6727 	case SCMD_READ_BLKLIM:
6728 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6729 		    "read block limits\n");
6730 		bp->b_flags |= B_READ;
6731 		bp->b_un.b_addr = (caddr_t)(un->un_rbl);
6732 		break;
6733 
6734 	case SCMD_TEST_UNIT_READY:
6735 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6736 		    "test unit ready\n");
6737 		bp->b_bcount = 0;
6738 		count = 0;
6739 		break;
6740 
6741 	case SCMD_DOORLOCK:
6742 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6743 		    "%s tape\n", (count & MR_LOCK) ? "lock" : "unlock");
6744 		bp->b_bcount = count = 0;
6745 		break;
6746 
6747 	case SCMD_READ_POSITION:
6748 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6749 		    "read position\n");
6750 		switch (un->un_read_pos_type) {
6751 		case LONG_POS:
6752 			count = sizeof (tape_position_long_t);
6753 			break;
6754 		case EXT_POS:
6755 			count = min(count, sizeof (tape_position_ext_t));
6756 			break;
6757 		case SHORT_POS:
6758 			count = sizeof (tape_position_t);
6759 			break;
6760 		default:
6761 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
6762 			    "Unknown read position type 0x%x in "
6763 			    "st_make_cmd()\n", un->un_read_pos_type);
6764 		}
6765 		bp->b_bcount = count;
6766 		bp->b_flags |= B_READ;
6767 		bp->b_un.b_addr = (caddr_t)un->un_read_pos_data;
6768 		break;
6769 
6770 	default:
6771 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
6772 		    "Unhandled scsi command 0x%x in st_cmd()\n", com);
6773 	}
6774 
6775 	mutex_exit(ST_MUTEX);
6776 
6777 	if (count > 0) {
6778 		/*
6779 		 * We're going to do actual I/O.
6780 		 * Set things up for physio.
6781 		 */
6782 		struct iovec aiov;
6783 		struct uio auio;
6784 		struct uio *uio = &auio;
6785 
6786 		bzero(&auio, sizeof (struct uio));
6787 		bzero(&aiov, sizeof (struct iovec));
6788 		aiov.iov_base = bp->b_un.b_addr;
6789 		aiov.iov_len = count;
6790 
6791 		uio->uio_iov = &aiov;
6792 		uio->uio_iovcnt = 1;
6793 		uio->uio_resid = aiov.iov_len;
6794 		uio->uio_segflg = UIO_SYSSPACE;
6795 
6796 		/*
6797 		 * Let physio do the rest...
6798 		 */
6799 		bp->b_forw = (struct buf *)(uintptr_t)com;
6800 		bp->b_back = NULL;
6801 		err = physio(st_strategy, bp, dev,
6802 		    (bp->b_flags & B_READ) ? B_READ : B_WRITE,
6803 		    st_minphys, uio);
6804 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6805 		    "st_cmd: physio returns %d\n", err);
6806 	} else {
6807 		/*
6808 		 * Mimic physio
6809 		 */
6810 		bp->b_forw = (struct buf *)(uintptr_t)com;
6811 		bp->b_back = NULL;
6812 		bp->b_edev = dev;
6813 		bp->b_dev = cmpdev(dev);
6814 		bp->b_blkno = 0;
6815 		bp->b_resid = 0;
6816 		(void) st_strategy(bp);
6817 		if (!wait) {
6818 			/*
6819 			 * This is an async command- the caller won't wait
6820 			 * and doesn't care about errors.
6821 			 */
6822 			mutex_enter(ST_MUTEX);
6823 			return (0);
6824 		}
6825 
6826 		/*
6827 		 * BugTraq #4260046
6828 		 * ----------------
6829 		 * Restore Solaris 2.5.1 behavior, namely call biowait
6830 		 * unconditionally. The old comment said...
6831 		 *
6832 		 * "if strategy was flagged with  persistent errors, we would
6833 		 *  have an error here, and the bp would never be sent, so we
6834 		 *  don't want to wait on a bp that was never sent...or hang"
6835 		 *
6836 		 * The new rationale, courtesy of Chitrank...
6837 		 *
6838 		 * "we should unconditionally biowait() here because
6839 		 *  st_strategy() will do a biodone() in the persistent error
6840 		 *  case and the following biowait() will return immediately.
6841 		 *  If not, in the case of "errors after pkt alloc" in
6842 		 *  st_start(), we will not biowait here which will cause the
6843 		 *  next biowait() to return immediately which will cause
6844 		 *  us to send out the next command. In the case where both of
6845 		 *  these use the sbuf, when the first command completes we'll
6846 		 *  free the packet attached to sbuf and the same pkt will
6847 		 *  get freed again when we complete the second command.
6848 		 *  see esc 518987.  BTW, it is necessary to do biodone() in
6849 		 *  st_start() for the pkt alloc failure case because physio()
6850 		 *  does biowait() and will hang if we don't do biodone()"
6851 		 */
6852 
6853 		err = biowait(bp);
6854 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6855 		    "st_cmd: biowait returns %d\n", err);
6856 	}
6857 	mutex_enter(ST_MUTEX);
6858 
6859 	un->un_sbuf_busy = 0;
6860 
6861 	/*
6862 	 * If was a space command need to update logical block position.
6863 	 * If the command failed such that positioning is invalid, Don't
6864 	 * update the position as the user must do this to validate the
6865 	 * position for data protection.
6866 	 */
6867 	if ((com == SCMD_SPACE) && (un->un_pos.pmode != invalid)) {
6868 		uchar_t status = un->un_status;
6869 		(void) st_update_block_pos(un);
6870 		un->un_status = status;
6871 	}
6872 
6873 	cv_signal(&un->un_sbuf_cv);
6874 	return (err);
6875 }
6876 
6877 static int
6878 st_set_compression(struct scsi_tape *un)
6879 {
6880 	int rval;
6881 	int turn_compression_on;
6882 	minor_t minor;
6883 
6884 	ST_FUNC(ST_DEVINFO, st_set_compression);
6885 
6886 	/*
6887 	 * Drive either dosn't have compression or it is controlled with
6888 	 * special density codes. Return ENOTTY so caller
6889 	 * knows nothing was done.
6890 	 */
6891 	if ((un->un_dp->options & ST_MODE_SEL_COMP) == 0) {
6892 		un->un_comp_page = 0;
6893 		return (ENOTTY);
6894 	}
6895 
6896 	/* set compression based on minor node opened */
6897 	minor = MT_DENSITY(un->un_dev);
6898 
6899 	/*
6900 	 * If this the compression density or
6901 	 * the drive has two densities and uses mode select for
6902 	 * control of compression turn on compression for MT_DENSITY2
6903 	 * as well.
6904 	 */
6905 	if ((minor == ST_COMPRESSION_DENSITY) ||
6906 	    (minor == MT_DENSITY(MT_DENSITY2)) &&
6907 	    (un->un_dp->densities[0] == un->un_dp->densities[1]) &&
6908 	    (un->un_dp->densities[2] == un->un_dp->densities[3]) &&
6909 	    (un->un_dp->densities[0] != un->un_dp->densities[2])) {
6910 
6911 		turn_compression_on = 1;
6912 	} else {
6913 		turn_compression_on = 0;
6914 	}
6915 
6916 	un->un_mspl->high_bl = (uchar_t)(un->un_bsize >> 16);
6917 	un->un_mspl->mid_bl  = (uchar_t)(un->un_bsize >> 8);
6918 	un->un_mspl->low_bl  = (uchar_t)(un->un_bsize);
6919 
6920 	/*
6921 	 * Need to determine which page does the device use for compression.
6922 	 * First try the data compression page. If this fails try the device
6923 	 * configuration page
6924 	 */
6925 
6926 	if ((un->un_comp_page & ST_DEV_DATACOMP_PAGE) == ST_DEV_DATACOMP_PAGE) {
6927 		rval = st_set_datacomp_page(un, turn_compression_on);
6928 		if (rval == EALREADY) {
6929 			return (rval);
6930 		}
6931 		if (rval != 0) {
6932 			if (un->un_status == KEY_ILLEGAL_REQUEST) {
6933 				/*
6934 				 * This device does not support data
6935 				 * compression page
6936 				 */
6937 				un->un_comp_page = ST_DEV_CONFIG_PAGE;
6938 			} else if (un->un_state >= ST_STATE_OPEN) {
6939 				un->un_pos.pmode = invalid;
6940 				rval = EIO;
6941 			} else {
6942 				rval = -1;
6943 			}
6944 		} else {
6945 			un->un_comp_page = ST_DEV_DATACOMP_PAGE;
6946 		}
6947 	}
6948 
6949 	if ((un->un_comp_page & ST_DEV_CONFIG_PAGE) == ST_DEV_CONFIG_PAGE) {
6950 		rval = st_set_devconfig_page(un, turn_compression_on);
6951 		if (rval == EALREADY) {
6952 			return (rval);
6953 		}
6954 		if (rval != 0) {
6955 			if (un->un_status == KEY_ILLEGAL_REQUEST) {
6956 				/*
6957 				 * This device does not support
6958 				 * compression at all advice the
6959 				 * user and unset ST_MODE_SEL_COMP
6960 				 */
6961 				un->un_dp->options &= ~ST_MODE_SEL_COMP;
6962 				un->un_comp_page = 0;
6963 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
6964 				    "Device Does Not Support Compression\n");
6965 			} else if (un->un_state >= ST_STATE_OPEN) {
6966 				un->un_pos.pmode = invalid;
6967 				rval = EIO;
6968 			} else {
6969 				rval = -1;
6970 			}
6971 		}
6972 	}
6973 
6974 	return (rval);
6975 }
6976 
6977 /*
6978  * set or unset compression thru device configuration page.
6979  */
6980 static int
6981 st_set_devconfig_page(struct scsi_tape *un, int compression_on)
6982 {
6983 	unsigned char cflag;
6984 	int rval = 0;
6985 
6986 
6987 	ST_FUNC(ST_DEVINFO, st_set_devconfig_page);
6988 
6989 	ASSERT(mutex_owned(ST_MUTEX));
6990 	/*
6991 	 * Figure what to set compression flag to.
6992 	 */
6993 	if (compression_on) {
6994 		/* They have selected a compression node */
6995 		if (un->un_dp->type == ST_TYPE_FUJI) {
6996 			cflag = 0x84;   /* use EDRC */
6997 		} else {
6998 			cflag = ST_DEV_CONFIG_DEF_COMP;
6999 		}
7000 	} else {
7001 		cflag = ST_DEV_CONFIG_NO_COMP;
7002 	}
7003 
7004 	/*
7005 	 * If compression is already set the way it was requested.
7006 	 * And if this not the first time we has tried.
7007 	 */
7008 	if ((cflag == un->un_mspl->page.dev.comp_alg) &&
7009 	    (un->un_comp_page == ST_DEV_DATACOMP_PAGE)) {
7010 		return (EALREADY);
7011 	}
7012 
7013 	un->un_mspl->page.dev.comp_alg = cflag;
7014 	/*
7015 	 * need to send mode select even if correct compression is
7016 	 * already set since need to set density code
7017 	 */
7018 
7019 #ifdef STDEBUG
7020 	if ((st_debug & 0xf) >= 6) {
7021 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
7022 		    "st_set_devconfig_page: sense data for mode select",
7023 		    (char *)un->un_mspl, sizeof (struct seq_mode));
7024 	}
7025 #endif
7026 	rval = st_gen_mode_select(un, un->un_mspl, sizeof (struct seq_mode));
7027 
7028 	return (rval);
7029 }
7030 
7031 /*
7032  * set/reset compression bit thru data compression page
7033  */
7034 static int
7035 st_set_datacomp_page(struct scsi_tape *un, int compression_on)
7036 {
7037 	int compression_on_already;
7038 	int rval = 0;
7039 
7040 
7041 	ST_FUNC(ST_DEVINFO, st_set_datacomp_page);
7042 
7043 	ASSERT(mutex_owned(ST_MUTEX));
7044 	/*
7045 	 * If drive is not capable of compression (at this time)
7046 	 * return EALREADY so caller doesn't think that this page
7047 	 * is not supported. This check is for drives that can
7048 	 * disable compression from the front panel or configuration.
7049 	 * I doubt that a drive that supports this page is not really
7050 	 * capable of compression.
7051 	 */
7052 	if (un->un_mspl->page.comp.dcc == 0) {
7053 		return (EALREADY);
7054 	}
7055 
7056 	/* See if compression currently turned on */
7057 	if (un->un_mspl->page.comp.dce) {
7058 		compression_on_already = 1;
7059 	} else {
7060 		compression_on_already = 0;
7061 	}
7062 
7063 	/*
7064 	 * If compression is already set the way it was requested.
7065 	 * And if this not the first time we has tried.
7066 	 */
7067 	if ((compression_on == compression_on_already) &&
7068 	    (un->un_comp_page == ST_DEV_DATACOMP_PAGE)) {
7069 		return (EALREADY);
7070 	}
7071 
7072 	/*
7073 	 * if we are already set to the appropriate compression
7074 	 * mode, don't set it again
7075 	 */
7076 	if (compression_on) {
7077 		/* compression selected */
7078 		un->un_mspl->page.comp.dce = 1;
7079 	} else {
7080 		un->un_mspl->page.comp.dce = 0;
7081 	}
7082 
7083 
7084 #ifdef STDEBUG
7085 	if ((st_debug & 0xf) >= 6) {
7086 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
7087 		    "st_set_datacomp_page: sense data for mode select",
7088 		    (char *)un->un_mspl, sizeof (struct seq_mode));
7089 	}
7090 #endif
7091 	rval = st_gen_mode_select(un, un->un_mspl, sizeof (struct seq_mode));
7092 
7093 	return (rval);
7094 }
7095 
7096 static int
7097 st_modesense(struct scsi_tape *un)
7098 {
7099 	int rval;
7100 	uchar_t page;
7101 
7102 	ST_FUNC(ST_DEVINFO, st_modesense);
7103 
7104 	page = un->un_comp_page;
7105 
7106 	switch (page) {
7107 	case ST_DEV_DATACOMP_PAGE:
7108 	case ST_DEV_CONFIG_PAGE: /* fall through */
7109 		rval = st_gen_mode_sense(un, page, un->un_mspl,
7110 		    sizeof (struct seq_mode));
7111 		break;
7112 
7113 	case ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE:
7114 		if (un->un_dp->options & ST_MODE_SEL_COMP) {
7115 			page = ST_DEV_DATACOMP_PAGE;
7116 			rval = st_gen_mode_sense(un, page, un->un_mspl,
7117 			    sizeof (struct seq_mode));
7118 			if (rval == 0 && un->un_mspl->page_code == page) {
7119 				un->un_comp_page = page;
7120 				break;
7121 			}
7122 			page = ST_DEV_CONFIG_PAGE;
7123 			rval = st_gen_mode_sense(un, page, un->un_mspl,
7124 			    sizeof (struct seq_mode));
7125 			if (rval == 0 && un->un_mspl->page_code == page) {
7126 				un->un_comp_page = page;
7127 				break;
7128 			}
7129 			un->un_dp->options &= ~ST_MODE_SEL_COMP;
7130 			un->un_comp_page = 0;
7131 		} else {
7132 			un->un_comp_page = 0;
7133 		}
7134 
7135 	default:	/* fall through */
7136 		rval = st_cmd(un->un_dev, SCMD_MODE_SENSE, MSIZE, SYNC_CMD);
7137 	}
7138 	return (rval);
7139 }
7140 
7141 static int
7142 st_modeselect(struct scsi_tape *un)
7143 {
7144 	int rval = 0;
7145 	int ix;
7146 
7147 	ST_FUNC(ST_DEVINFO, st_modeselect);
7148 
7149 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7150 	    "st_modeselect(dev = 0x%lx): density = 0x%x\n",
7151 	    un->un_dev, un->un_mspl->density);
7152 
7153 	ASSERT(mutex_owned(ST_MUTEX));
7154 
7155 	/*
7156 	 * The parameter list should be the same for all of the
7157 	 * cases that follow so set them here
7158 	 *
7159 	 * Try mode select first if if fails set fields manually
7160 	 */
7161 	rval = st_modesense(un);
7162 	if (rval != 0) {
7163 		ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
7164 		    "st_modeselect: First mode sense failed\n");
7165 		un->un_mspl->bd_len  = 8;
7166 		un->un_mspl->high_nb = 0;
7167 		un->un_mspl->mid_nb  = 0;
7168 		un->un_mspl->low_nb  = 0;
7169 	}
7170 	un->un_mspl->high_bl = (uchar_t)(un->un_bsize >> 16);
7171 	un->un_mspl->mid_bl  = (uchar_t)(un->un_bsize >> 8);
7172 	un->un_mspl->low_bl  = (uchar_t)(un->un_bsize);
7173 
7174 
7175 	/*
7176 	 * If configured to use a specific density code for a media type.
7177 	 * curdens is previously set by the minor node opened.
7178 	 * If the media type doesn't match the minor node we change it so it
7179 	 * looks like the correct one was opened.
7180 	 */
7181 	if (un->un_dp->options & ST_KNOWS_MEDIA) {
7182 		uchar_t best;
7183 
7184 		for (best = 0xff, ix = 0; ix < NDENSITIES; ix++) {
7185 			if (un->un_mspl->media_type ==
7186 			    un->un_dp->mediatype[ix]) {
7187 				best = ix;
7188 				/*
7189 				 * It matches but it might not be the only one.
7190 				 * Use the highest matching media type but not
7191 				 * to exceed the density selected by the open.
7192 				 */
7193 				if (ix < un->un_curdens) {
7194 					continue;
7195 				}
7196 				un->un_curdens = ix;
7197 				break;
7198 			}
7199 		}
7200 		/* If a match was found best will not be 0xff any more */
7201 		if (best < NDENSITIES) {
7202 			ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
7203 			    "found media 0x%X using density 0x%X\n",
7204 			    un->un_mspl->media_type,
7205 			    un->un_dp->densities[best]);
7206 			un->un_mspl->density = un->un_dp->densities[best];
7207 		} else {
7208 			/* Otherwise set density based on minor node opened */
7209 			un->un_mspl->density =
7210 			    un->un_dp->densities[un->un_curdens];
7211 		}
7212 	} else {
7213 		un->un_mspl->density = un->un_dp->densities[un->un_curdens];
7214 	}
7215 
7216 	if (un->un_dp->options & ST_NOBUF) {
7217 		un->un_mspl->bufm = 0;
7218 	} else {
7219 		un->un_mspl->bufm = 1;
7220 	}
7221 
7222 	rval = st_set_compression(un);
7223 
7224 	/*
7225 	 * If st_set_compression returned invalid or already it
7226 	 * found no need to do the mode select.
7227 	 * So do it here.
7228 	 */
7229 	if ((rval == ENOTTY) || (rval == EALREADY)) {
7230 
7231 		/* Zero non-writeable fields */
7232 		un->un_mspl->data_len = 0;
7233 		un->un_mspl->media_type = 0;
7234 		un->un_mspl->wp = 0;
7235 
7236 		/* need to set the density code */
7237 		rval = st_cmd(un->un_dev, SCMD_MODE_SELECT, MSIZE, SYNC_CMD);
7238 		if (rval != 0) {
7239 			if (un->un_state >= ST_STATE_OPEN) {
7240 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
7241 				    "unable to set tape mode\n");
7242 				un->un_pos.pmode = invalid;
7243 				rval = EIO;
7244 			} else {
7245 				rval = -1;
7246 			}
7247 		}
7248 	}
7249 
7250 	/*
7251 	 * The spec recommends to send a mode sense after a mode select
7252 	 */
7253 	(void) st_modesense(un);
7254 
7255 	ASSERT(mutex_owned(ST_MUTEX));
7256 
7257 	return (rval);
7258 }
7259 
7260 /*
7261  * st_gen_mode_sense
7262  *
7263  * generic mode sense.. it allows for any page
7264  */
7265 static int
7266 st_gen_mode_sense(struct scsi_tape *un, int page, struct seq_mode *page_data,
7267     int page_size)
7268 {
7269 
7270 	int r;
7271 	char	cdb[CDB_GROUP0];
7272 	struct uscsi_cmd *com;
7273 
7274 	ST_FUNC(ST_DEVINFO, st_gen_mode_sense);
7275 
7276 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
7277 
7278 	bzero(cdb, CDB_GROUP0);
7279 	cdb[0] = SCMD_MODE_SENSE;
7280 	cdb[2] = (char)page;
7281 	cdb[4] = (char)page_size;
7282 
7283 	com->uscsi_cdb = cdb;
7284 	com->uscsi_cdblen = CDB_GROUP0;
7285 	com->uscsi_bufaddr = (caddr_t)page_data;
7286 	com->uscsi_buflen = page_size;
7287 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
7288 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
7289 
7290 	r = st_ioctl_cmd(un->un_dev, com, FKIOCTL);
7291 	kmem_free(com, sizeof (*com));
7292 	return (r);
7293 }
7294 
7295 /*
7296  * st_gen_mode_select
7297  *
7298  * generic mode select.. it allows for any page
7299  */
7300 static int
7301 st_gen_mode_select(struct scsi_tape *un, struct seq_mode *page_data,
7302     int page_size)
7303 {
7304 
7305 	int r;
7306 	char cdb[CDB_GROUP0];
7307 	struct uscsi_cmd *com;
7308 
7309 	ST_FUNC(ST_DEVINFO, st_gen_mode_select);
7310 
7311 	/* Zero non-writeable fields */
7312 	page_data->data_len = 0;
7313 	page_data->media_type = 0;
7314 	page_data->wp = 0;
7315 
7316 	/*
7317 	 * If mode select has any page data, zero the ps (Page Savable) bit.
7318 	 */
7319 	if (page_size > MSIZE) {
7320 		page_data->ps = 0;
7321 	}
7322 
7323 
7324 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
7325 
7326 	/*
7327 	 * then, do a mode select to set what ever info
7328 	 */
7329 	bzero(cdb, CDB_GROUP0);
7330 	cdb[0] = SCMD_MODE_SELECT;
7331 	cdb[1] = 0x10;		/* set PF bit for many third party drives */
7332 	cdb[4] = (char)page_size;
7333 
7334 	com->uscsi_cdb = cdb;
7335 	com->uscsi_cdblen = CDB_GROUP0;
7336 	com->uscsi_bufaddr = (caddr_t)page_data;
7337 	com->uscsi_buflen = page_size;
7338 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
7339 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_WRITE;
7340 
7341 	r = st_ioctl_cmd(un->un_dev, com, FKIOCTL);
7342 
7343 	kmem_free(com, sizeof (*com));
7344 	return (r);
7345 }
7346 
7347 /*
7348  * Changes devices blocksize and bsize to requested blocksize nblksz.
7349  * Returns returned value from first failed call or zero on success.
7350  */
7351 static int
7352 st_change_block_size(dev_t dev, uint32_t nblksz)
7353 {
7354 	struct seq_mode *current;
7355 	int rval;
7356 	uint32_t oldblksz;
7357 
7358 	GET_SOFT_STATE(dev);
7359 
7360 	ST_FUNC(ST_DEVINFO, st_change_block_size);
7361 
7362 	current = kmem_zalloc(MSIZE, KM_SLEEP);
7363 
7364 	/* Read current settings */
7365 	rval = st_gen_mode_sense(un, 0, current, MSIZE);
7366 	if (rval != 0) {
7367 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
7368 		    "mode sense for change block size failed: rval = %d", rval);
7369 		goto finish;
7370 	}
7371 
7372 	/* Figure the current block size */
7373 	oldblksz =
7374 	    (current->high_bl << 16) |
7375 	    (current->mid_bl << 8) |
7376 	    (current->low_bl);
7377 
7378 	/* If current block size is the same as requested were done */
7379 	if (oldblksz == nblksz) {
7380 		un->un_bsize = nblksz;
7381 		rval = 0;
7382 		goto finish;
7383 	}
7384 
7385 	/* Change to requested block size */
7386 	current->high_bl = (uchar_t)(nblksz >> 16);
7387 	current->mid_bl  = (uchar_t)(nblksz >> 8);
7388 	current->low_bl  = (uchar_t)(nblksz);
7389 
7390 	/* Attempt to change block size */
7391 	rval = st_gen_mode_select(un, current, MSIZE);
7392 	if (rval != 0) {
7393 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
7394 		    "Set new block size failed: rval = %d", rval);
7395 		goto finish;
7396 	}
7397 
7398 	/* Read back and verify setting */
7399 	rval = st_modesense(un);
7400 	if (rval == 0) {
7401 		un->un_bsize =
7402 		    (un->un_mspl->high_bl << 16) |
7403 		    (un->un_mspl->mid_bl << 8) |
7404 		    (un->un_mspl->low_bl);
7405 
7406 		if (un->un_bsize != nblksz) {
7407 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
7408 			    "Blocksize set does not equal requested blocksize"
7409 			    "(read: %u requested: %u)\n", nblksz, un->un_bsize);
7410 			rval = EIO;
7411 		}
7412 	}
7413 finish:
7414 	kmem_free(current, MSIZE);
7415 	return (rval);
7416 }
7417 
7418 
7419 static void
7420 st_init(struct scsi_tape *un)
7421 {
7422 	ST_FUNC(ST_DEVINFO, st_init);
7423 
7424 	ASSERT(mutex_owned(ST_MUTEX));
7425 
7426 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7427 	    "st_init(): dev = 0x%lx, will reset fileno, blkno, eof\n",
7428 	    un->un_dev);
7429 
7430 	un->un_pos.blkno = 0;
7431 	un->un_pos.fileno = 0;
7432 	un->un_lastop = ST_OP_NIL;
7433 	un->un_pos.eof = ST_NO_EOF;
7434 	un->un_pwr_mgmt = ST_PWR_NORMAL;
7435 	if (st_error_level != SCSI_ERR_ALL) {
7436 		if (DEBUGGING) {
7437 			st_error_level = SCSI_ERR_ALL;
7438 		} else {
7439 			st_error_level = SCSI_ERR_RETRYABLE;
7440 		}
7441 	}
7442 }
7443 
7444 
7445 static void
7446 st_make_cmd(struct scsi_tape *un, struct buf *bp, int (*func)(caddr_t))
7447 {
7448 	struct scsi_pkt *pkt;
7449 	struct uscsi_cmd *ucmd;
7450 	int count, tval = 0;
7451 	uint_t addr = 0;
7452 	int flags = 0;
7453 	int cdb_len = CDB_GROUP0; /* default */
7454 	uchar_t com;
7455 	char fixbit;
7456 
7457 	ST_FUNC(ST_DEVINFO, st_make_cmd);
7458 
7459 	ASSERT(mutex_owned(ST_MUTEX));
7460 
7461 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7462 	    "st_make_cmd(): dev = 0x%lx\n", un->un_dev);
7463 
7464 
7465 	/*
7466 	 * fixbit is for setting the Fixed Mode and Suppress Incorrect
7467 	 * Length Indicator bits on read/write commands, for setting
7468 	 * the Long bit on erase commands, and for setting the Code
7469 	 * Field bits on space commands.
7470 	 * XXX why do we set lastop here?
7471 	 */
7472 
7473 	if (bp != un->un_sbufp) {		/* regular raw I/O */
7474 		int stat_size = (un->un_arq_enabled ?
7475 		    sizeof (struct scsi_arq_status) : 1);
7476 		pkt = scsi_init_pkt(ROUTE, NULL, bp,
7477 		    CDB_GROUP0, stat_size, 0, 0, func, (caddr_t)un);
7478 		if (pkt == NULL) {
7479 			goto exit;
7480 		}
7481 		SET_BP_PKT(bp, pkt);
7482 		if (un->un_bsize == 0) {
7483 			count = bp->b_bcount;
7484 			fixbit = 0;
7485 		} else {
7486 			count = bp->b_bcount / un->un_bsize;
7487 			fixbit = 1;
7488 		}
7489 		if (bp->b_flags & B_READ) {
7490 			com = SCMD_READ;
7491 			un->un_lastop = ST_OP_READ;
7492 			if ((un->un_bsize == 0) && /* Not Fixed Block */
7493 			    (un->un_dp->options & ST_READ_IGNORE_ILI)) {
7494 				fixbit = 2;
7495 			}
7496 		} else {
7497 			com = SCMD_WRITE;
7498 			un->un_lastop = ST_OP_WRITE;
7499 		}
7500 
7501 		tval = un->un_dp->io_timeout;
7502 
7503 		/*
7504 		 * For really large xfers, increase timeout
7505 		 */
7506 		if (bp->b_bcount > (10 * ONE_MEG))
7507 			tval *= bp->b_bcount/(10 * ONE_MEG);
7508 
7509 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7510 		    "%s %d amt 0x%lx\n", (com == SCMD_WRITE) ?
7511 		    wr_str: rd_str, un->un_pos.blkno, bp->b_bcount);
7512 
7513 	} else if ((ucmd = BP_UCMD(bp)) != NULL) {
7514 		/*
7515 		 * uscsi - build command, allocate scsi resources
7516 		 */
7517 		st_make_uscsi_cmd(un, ucmd, bp, func);
7518 		goto exit;
7519 
7520 	} else {				/* special I/O */
7521 		int stat_size = (un->un_arq_enabled ?
7522 		    sizeof (struct scsi_arq_status) : 1);
7523 		struct buf *allocbp = NULL;
7524 		com = (uchar_t)(uintptr_t)bp->b_forw;
7525 		count = bp->b_bcount;
7526 
7527 		switch (com) {
7528 		case SCMD_READ:
7529 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7530 			    "special read %d\n", count);
7531 			if (un->un_bsize == 0) {
7532 				fixbit = 2;	/* suppress SILI */
7533 			} else {
7534 				fixbit = 1;	/* Fixed Block Mode */
7535 				count /= un->un_bsize;
7536 			}
7537 			allocbp = bp;
7538 			un->un_lastop = ST_OP_READ;
7539 			tval = un->un_dp->io_timeout;
7540 			break;
7541 
7542 		case SCMD_WRITE:
7543 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7544 			    "special write %d\n", count);
7545 			if (un->un_bsize != 0) {
7546 				fixbit = 1;	/* Fixed Block Mode */
7547 				count /= un->un_bsize;
7548 			} else {
7549 				fixbit = 0;
7550 			}
7551 			allocbp = bp;
7552 			un->un_lastop = ST_OP_WRITE;
7553 			tval = un->un_dp->io_timeout;
7554 			break;
7555 
7556 		case SCMD_WRITE_FILE_MARK:
7557 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7558 			    "write %d file marks\n", count);
7559 			un->un_lastop = ST_OP_WEOF;
7560 			fixbit = 0;
7561 			tval = un->un_dp->io_timeout;
7562 			break;
7563 
7564 		case SCMD_REWIND:
7565 			if (bp->b_flags & B_ASYNC) {
7566 				fixbit = 1;
7567 			} else {
7568 				fixbit = 0;
7569 			}
7570 			count = 0;
7571 			un->un_lastop = ST_OP_CTL;
7572 			tval = un->un_dp->rewind_timeout;
7573 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7574 			    "rewind\n");
7575 			break;
7576 
7577 		case SCMD_SPACE:
7578 			fixbit = SPACE_TYPE(count);
7579 			count = (int)SPACE_CNT(count);
7580 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7581 			    "space %s %d from file %d blk %d\n",
7582 			    space_strs[fixbit & 7], count,
7583 			    un->un_pos.fileno, un->un_pos.blkno);
7584 			un->un_lastop = ST_OP_CTL;
7585 			tval = un->un_dp->space_timeout;
7586 			break;
7587 
7588 		case SCMD_LOAD:
7589 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7590 			    "%s tape\n", (count & LD_LOAD) ? "load" : "unload");
7591 			fixbit = 0;
7592 
7593 			/* Loading or Unloading */
7594 			if (count & LD_LOAD) {
7595 				tval = un->un_dp->load_timeout;
7596 			} else {
7597 				tval = un->un_dp->unload_timeout;
7598 			}
7599 			/* Is Retension requested */
7600 			if (count & LD_RETEN) {
7601 				tval += un->un_dp->rewind_timeout;
7602 			}
7603 			un->un_lastop = ST_OP_CTL;
7604 			break;
7605 
7606 		case SCMD_ERASE:
7607 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7608 			    "erase tape\n");
7609 			count = 0;
7610 			/*
7611 			 * We support long erase only
7612 			 */
7613 			fixbit = 1;
7614 			tval = un->un_dp->erase_timeout;
7615 			un->un_lastop = ST_OP_CTL;
7616 			break;
7617 
7618 		case SCMD_MODE_SENSE:
7619 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7620 			    "mode sense\n");
7621 			allocbp = bp;
7622 			fixbit = 0;
7623 			tval = un->un_dp->non_motion_timeout;
7624 			un->un_lastop = ST_OP_CTL;
7625 			break;
7626 
7627 		case SCMD_MODE_SELECT:
7628 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7629 			    "mode select\n");
7630 			allocbp = bp;
7631 			fixbit = 0;
7632 			tval = un->un_dp->non_motion_timeout;
7633 			un->un_lastop = ST_OP_CTL;
7634 			break;
7635 
7636 		case SCMD_RESERVE:
7637 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7638 			    "reserve\n");
7639 			fixbit = 0;
7640 			tval = un->un_dp->non_motion_timeout;
7641 			un->un_lastop = ST_OP_CTL;
7642 			break;
7643 
7644 		case SCMD_RELEASE:
7645 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7646 			    "release\n");
7647 			fixbit = 0;
7648 			tval = un->un_dp->non_motion_timeout;
7649 			un->un_lastop = ST_OP_CTL;
7650 			break;
7651 
7652 		case SCMD_READ_BLKLIM:
7653 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7654 			    "read block limits\n");
7655 			allocbp = bp;
7656 			fixbit = count = 0;
7657 			tval = un->un_dp->non_motion_timeout;
7658 			un->un_lastop = ST_OP_CTL;
7659 			break;
7660 
7661 		case SCMD_TEST_UNIT_READY:
7662 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7663 			    "test unit ready\n");
7664 			fixbit = 0;
7665 			tval = un->un_dp->non_motion_timeout;
7666 			un->un_lastop = ST_OP_CTL;
7667 			break;
7668 
7669 		case SCMD_DOORLOCK:
7670 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7671 			    "prevent/allow media removal\n");
7672 			fixbit = 0;
7673 			tval = un->un_dp->non_motion_timeout;
7674 			un->un_lastop = ST_OP_CTL;
7675 			break;
7676 
7677 		case SCMD_READ_POSITION:
7678 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7679 			    "read position\n");
7680 			fixbit = un->un_read_pos_type;
7681 			cdb_len = CDB_GROUP1;
7682 			tval = un->un_dp->non_motion_timeout;
7683 			allocbp = bp;
7684 			un->un_lastop = ST_OP_CTL;
7685 			switch (un->un_read_pos_type) {
7686 			case LONG_POS:
7687 				count = 0;
7688 				break;
7689 			case EXT_POS:
7690 				count = sizeof (tape_position_ext_t);
7691 				break;
7692 			case SHORT_POS:
7693 				count = 0;
7694 				break;
7695 			default:
7696 				ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
7697 				    "Unknown read position type 0x%x in "
7698 				    " st_make_cmd()\n", un->un_read_pos_type);
7699 			}
7700 			break;
7701 
7702 		default:
7703 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
7704 			    "Unhandled scsi command 0x%x in st_make_cmd()\n",
7705 			    com);
7706 		}
7707 		pkt = scsi_init_pkt(ROUTE, NULL, allocbp, cdb_len, stat_size,
7708 		    0, 0, func, (caddr_t)un);
7709 		if (pkt == NULL) {
7710 			goto exit;
7711 		}
7712 		if (allocbp) {
7713 			ASSERT(geterror(allocbp) == 0);
7714 		}
7715 
7716 	}
7717 
7718 
7719 	(void) scsi_setup_cdb((union scsi_cdb *)pkt->pkt_cdbp,
7720 	    com, addr, (uint_t)count, 0);
7721 	FILL_SCSI1_LUN(un->un_sd, pkt);
7722 	/*
7723 	 * Initialize the SILI/Fixed bits of the byte 1 of cdb.
7724 	 */
7725 	((union scsi_cdb *)(pkt->pkt_cdbp))->t_code = fixbit;
7726 	pkt->pkt_flags = flags;
7727 
7728 #ifdef STDEBUG
7729 	if ((st_debug & 0xf) >= 6) {
7730 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
7731 		    "cmd cdb", (char *)pkt->pkt_cdbp, cdb_len);
7732 	}
7733 #endif
7734 
7735 	/*
7736 	 * If ST_SHORT_FILEMARKS bit is ON for EXABYTE
7737 	 * device, set the Vendor Unique bit to
7738 	 * write Short File Mark.
7739 	 */
7740 	if (com == SCMD_WRITE_FILE_MARK &&
7741 	    un->un_dp->options & ST_SHORT_FILEMARKS) {
7742 		switch (un->un_dp->type) {
7743 		case ST_TYPE_EXB8500:
7744 		case ST_TYPE_EXABYTE:
7745 			/*
7746 			 * Now the Vendor Unique bit 7 in Byte 5 of CDB
7747 			 * is set to to write Short File Mark
7748 			 */
7749 			((union scsi_cdb *)pkt->pkt_cdbp)->g0_vu_1 = 1;
7750 			break;
7751 
7752 		default:
7753 			/*
7754 			 * Well, if ST_SHORT_FILEMARKS is set for other
7755 			 * tape drives, it is just ignored
7756 			 */
7757 			break;
7758 		}
7759 	}
7760 	ASSERT(tval);
7761 	pkt->pkt_time = tval;
7762 	pkt->pkt_comp = st_intr;
7763 	pkt->pkt_private = (opaque_t)bp;
7764 
7765 	SET_BP_PKT(bp, pkt);
7766 
7767 exit:
7768 	ASSERT(mutex_owned(ST_MUTEX));
7769 }
7770 
7771 
7772 /*
7773  * Build a command based on a uscsi command;
7774  */
7775 static void
7776 st_make_uscsi_cmd(struct scsi_tape *un, struct uscsi_cmd *ucmd,
7777     struct buf *bp, int (*func)(caddr_t))
7778 {
7779 	struct scsi_pkt *pkt;
7780 	caddr_t cdb;
7781 	int	cdblen;
7782 	int stat_size;
7783 
7784 	ST_FUNC(ST_DEVINFO, st_make_uscsi_cmd);
7785 
7786 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7787 	    "st_make_uscsi_cmd(): dev = 0x%lx\n", un->un_dev);
7788 
7789 	if (ucmd->uscsi_flags & USCSI_RQENABLE) {
7790 		stat_size = (un->un_arq_enabled ?
7791 		    sizeof (struct scsi_arq_status) : 1);
7792 	} else {
7793 		stat_size = 1;
7794 	}
7795 
7796 	ASSERT(mutex_owned(ST_MUTEX));
7797 
7798 	cdb = ucmd->uscsi_cdb;
7799 	cdblen = ucmd->uscsi_cdblen;
7800 
7801 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7802 	    "st_make_uscsi_cmd: buflen=%ld bcount=%ld\n",
7803 	    ucmd->uscsi_buflen, bp->b_bcount);
7804 	pkt = scsi_init_pkt(ROUTE, NULL,
7805 	    (bp->b_bcount > 0) ? bp : NULL,
7806 	    cdblen, stat_size, 0, 0, func, (caddr_t)un);
7807 	if (pkt == NULL) {
7808 		goto exit;
7809 	}
7810 
7811 	bcopy(cdb, pkt->pkt_cdbp, (uint_t)cdblen);
7812 
7813 #ifdef STDEBUG
7814 	if ((st_debug & 0xf) >= 6) {
7815 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
7816 		    "pkt_cdbp", (char *)cdb, cdblen);
7817 	}
7818 #endif
7819 
7820 	if (ucmd->uscsi_flags & USCSI_SILENT) {
7821 		pkt->pkt_flags |= FLAG_SILENT;
7822 	}
7823 
7824 	pkt->pkt_time = ucmd->uscsi_timeout;
7825 	pkt->pkt_comp = st_intr;
7826 	pkt->pkt_private = (opaque_t)bp;
7827 
7828 	SET_BP_PKT(bp, pkt);
7829 exit:
7830 	ASSERT(mutex_owned(ST_MUTEX));
7831 }
7832 
7833 
7834 /*
7835  * restart cmd currently at the head of the runq
7836  *
7837  * If scsi_transport() succeeds or the retries
7838  * count exhausted, restore the throttle that was
7839  * zeroed out in st_handle_intr_busy().
7840  *
7841  */
7842 static void
7843 st_intr_restart(void *arg)
7844 {
7845 	struct scsi_tape *un = arg;
7846 	struct buf *bp;
7847 	int status = TRAN_ACCEPT;
7848 
7849 	mutex_enter(ST_MUTEX);
7850 
7851 	ST_FUNC(ST_DEVINFO, st_intr_restart);
7852 
7853 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7854 	    "st_intr_restart(), un = 0x%p\n", (void *)un);
7855 
7856 	un->un_hib_tid = 0;
7857 
7858 	/*
7859 	 * move from waitq to runq, if there is anything on the waitq
7860 	 */
7861 	if ((bp = un->un_quef) == NULL) {
7862 		mutex_exit(ST_MUTEX);
7863 		return;
7864 	}
7865 
7866 	/*
7867 	 * Here we know :
7868 	 *	throttle = 0, via st_handle_intr_busy
7869 	 */
7870 
7871 	if (un->un_quel == bp) {
7872 		un->un_quel = NULL;
7873 		un->un_quef = NULL;	/* we know it's the first one */
7874 	} else {
7875 		un->un_quef = bp->b_actf;
7876 	}
7877 	bp->b_actf = NULL;
7878 
7879 	if (un->un_runqf) {
7880 		/*
7881 		 * not good, we don't want to requeue something after
7882 		 * another.
7883 		 */
7884 		mutex_exit(ST_MUTEX);
7885 		goto done_error;
7886 	} else {
7887 		un->un_runqf = bp;
7888 		un->un_runql = bp;
7889 	}
7890 
7891 	ST_DO_KSTATS(bp, kstat_waitq_to_runq);
7892 
7893 	mutex_exit(ST_MUTEX);
7894 
7895 	status = scsi_transport(BP_PKT(bp));
7896 
7897 	mutex_enter(ST_MUTEX);
7898 
7899 	if (status != TRAN_ACCEPT) {
7900 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
7901 		mutex_exit(ST_MUTEX);
7902 
7903 		if (status == TRAN_BUSY) {
7904 			if (st_handle_intr_busy(un, bp,
7905 			    ST_TRAN_BUSY_TIMEOUT) == 0)
7906 				return;	/* timeout is setup again */
7907 		}
7908 
7909 	} else {
7910 		un->un_tran_retry_ct = 0;
7911 		if (un->un_last_throttle) {
7912 			un->un_throttle = un->un_last_throttle;
7913 		}
7914 		mutex_exit(ST_MUTEX);
7915 		return;
7916 	}
7917 
7918 done_error:
7919 	ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
7920 	    "restart transport rejected\n");
7921 	bp->b_resid = bp->b_bcount;
7922 
7923 #ifndef __lock_lint
7924 	/*
7925 	 * warlock doesn't understand this potential
7926 	 * recursion?
7927 	 */
7928 	mutex_enter(ST_MUTEX);
7929 	if (un->un_last_throttle) {
7930 		un->un_throttle = un->un_last_throttle;
7931 	}
7932 	if (status != TRAN_ACCEPT)
7933 		ST_DO_ERRSTATS(un, st_transerrs);
7934 	ST_DO_KSTATS(bp, kstat_waitq_exit);
7935 	SET_PE_FLAG(un);
7936 	st_bioerror(bp, EIO);
7937 	st_done_and_mutex_exit(un, bp);
7938 #endif
7939 	ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
7940 	    "busy restart aborted\n");
7941 }
7942 
7943 /*
7944  * st_check_media():
7945  * Periodically check the media state using scsi_watch service;
7946  * this service calls back after TUR and possibly request sense
7947  * the callback handler (st_media_watch_cb()) decodes the request sense
7948  * data (if any)
7949  */
7950 
7951 static int
7952 st_check_media(dev_t dev, enum mtio_state state)
7953 {
7954 	int rval = 0;
7955 	enum mtio_state	prev_state;
7956 	opaque_t token = NULL;
7957 
7958 	GET_SOFT_STATE(dev);
7959 
7960 	ST_FUNC(ST_DEVINFO, st_check_media);
7961 
7962 	mutex_enter(ST_MUTEX);
7963 
7964 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
7965 	    "st_check_media:state=%x, mediastate=%x\n",
7966 	    state, un->un_mediastate);
7967 
7968 	prev_state = un->un_mediastate;
7969 
7970 	/*
7971 	 * is there anything to do?
7972 	 */
7973 retry:
7974 	if (state == un->un_mediastate || un->un_mediastate == MTIO_NONE) {
7975 		/*
7976 		 * submit the request to the scsi_watch service;
7977 		 * scsi_media_watch_cb() does the real work
7978 		 */
7979 		mutex_exit(ST_MUTEX);
7980 		token = scsi_watch_request_submit(ST_SCSI_DEVP,
7981 		    st_check_media_time, SENSE_LENGTH,
7982 		    st_media_watch_cb, (caddr_t)dev);
7983 		if (token == NULL) {
7984 			rval = EAGAIN;
7985 			goto done;
7986 		}
7987 		mutex_enter(ST_MUTEX);
7988 
7989 		un->un_swr_token = token;
7990 		un->un_specified_mediastate = state;
7991 
7992 		/*
7993 		 * now wait for media change
7994 		 * we will not be signalled unless mediastate == state but it
7995 		 * still better to test for this condition, since there
7996 		 * is a 5 sec cv_broadcast delay when
7997 		 *  mediastate == MTIO_INSERTED
7998 		 */
7999 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8000 		    "st_check_media:waiting for media state change\n");
8001 		while (un->un_mediastate == state) {
8002 			if (cv_wait_sig(&un->un_state_cv, ST_MUTEX) == 0) {
8003 				mutex_exit(ST_MUTEX);
8004 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8005 				    "st_check_media:waiting for media state "
8006 				    "was interrupted\n");
8007 				rval = EINTR;
8008 				goto done;
8009 			}
8010 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8011 			    "st_check_media:received signal, state=%x\n",
8012 			    un->un_mediastate);
8013 		}
8014 	}
8015 
8016 	/*
8017 	 * if we transitioned to MTIO_INSERTED, media has really been
8018 	 * inserted.  If TUR fails, it is probably a exabyte slow spin up.
8019 	 * Reset and retry the state change.  If everything is ok, replay
8020 	 * the open() logic.
8021 	 */
8022 	if ((un->un_mediastate == MTIO_INSERTED) &&
8023 	    (un->un_state == ST_STATE_OFFLINE)) {
8024 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8025 		    "st_check_media: calling st_cmd to confirm inserted\n");
8026 
8027 		/*
8028 		 * set this early so that TUR will make it through strategy
8029 		 * without triggering a st_tape_init().  We needed it set
8030 		 * before calling st_tape_init() ourselves anyway.  If TUR
8031 		 * fails, set it back
8032 		 */
8033 		un->un_state = ST_STATE_INITIALIZING;
8034 
8035 		/*
8036 		 * If not reserved fail as getting reservation conflict
8037 		 * will make this hang forever.
8038 		 */
8039 		if ((un->un_rsvd_status &
8040 		    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
8041 			mutex_exit(ST_MUTEX);
8042 			rval = EACCES;
8043 			goto done;
8044 		}
8045 		rval = st_cmd(dev, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
8046 		if (rval == EACCES) {
8047 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8048 			    "st_check_media: TUR got Reservation Conflict\n");
8049 			mutex_exit(ST_MUTEX);
8050 			goto done;
8051 		}
8052 		if (rval) {
8053 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8054 			    "st_check_media: TUR failed, going to retry\n");
8055 			un->un_mediastate = prev_state;
8056 			un->un_state = ST_STATE_OFFLINE;
8057 			goto retry;
8058 		}
8059 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8060 		    "st_check_media: media inserted\n");
8061 
8062 		/* this also rewinds the tape */
8063 		rval = st_tape_init(dev);
8064 		if (rval != 0) {
8065 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8066 			    "st_check_media : OFFLINE init failure ");
8067 			un->un_state = ST_STATE_OFFLINE;
8068 			un->un_pos.pmode = invalid;
8069 		} else {
8070 			un->un_state = ST_STATE_OPEN_PENDING_IO;
8071 			un->un_pos.fileno = 0;
8072 			un->un_pos.blkno = 0;
8073 			un->un_pos.lgclblkno = 0;
8074 		}
8075 	} else if ((un->un_mediastate == MTIO_EJECTED) &&
8076 	    (un->un_state != ST_STATE_OFFLINE)) {
8077 		/*
8078 		 * supported devices must be rewound before ejection
8079 		 * rewind resets fileno & blkno
8080 		 */
8081 		un->un_laststate = un->un_state;
8082 		un->un_state = ST_STATE_OFFLINE;
8083 	}
8084 	mutex_exit(ST_MUTEX);
8085 done:
8086 	if (token) {
8087 		(void) scsi_watch_request_terminate(token,
8088 		    SCSI_WATCH_TERMINATE_WAIT);
8089 		mutex_enter(ST_MUTEX);
8090 		un->un_swr_token = (opaque_t)NULL;
8091 		mutex_exit(ST_MUTEX);
8092 	}
8093 
8094 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG, "st_check_media: done\n");
8095 
8096 	return (rval);
8097 }
8098 
8099 /*
8100  * st_media_watch_cb() is called by scsi_watch_thread for
8101  * verifying the request sense data (if any)
8102  */
8103 static int
8104 st_media_watch_cb(caddr_t arg, struct scsi_watch_result *resultp)
8105 {
8106 	struct scsi_status *statusp = resultp->statusp;
8107 	struct scsi_extended_sense *sensep = resultp->sensep;
8108 	uchar_t actual_sense_length = resultp->actual_sense_length;
8109 	struct scsi_tape *un;
8110 	enum mtio_state state = MTIO_NONE;
8111 	int instance;
8112 	dev_t dev = (dev_t)arg;
8113 
8114 	instance = MTUNIT(dev);
8115 	if ((un = ddi_get_soft_state(st_state, instance)) == NULL) {
8116 		return (-1);
8117 	}
8118 
8119 	mutex_enter(ST_MUTEX);
8120 	ST_FUNC(ST_DEVINFO, st_media_watch_cb);
8121 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8122 	    "st_media_watch_cb: status=%x, sensep=%p, len=%x\n",
8123 	    *((char *)statusp), (void *)sensep,
8124 	    actual_sense_length);
8125 
8126 
8127 	/*
8128 	 * if there was a check condition then sensep points to valid
8129 	 * sense data
8130 	 * if status was not a check condition but a reservation or busy
8131 	 * status then the new state is MTIO_NONE
8132 	 */
8133 	if (sensep) {
8134 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8135 		    "st_media_watch_cb: KEY=%x, ASC=%x, ASCQ=%x\n",
8136 		    sensep->es_key, sensep->es_add_code, sensep->es_qual_code);
8137 
8138 		switch (un->un_dp->type) {
8139 		default:
8140 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8141 			    "st_media_watch_cb: unknown drive type %d, "
8142 			    "default to ST_TYPE_HP\n", un->un_dp->type);
8143 		/* FALLTHROUGH */
8144 
8145 		case ST_TYPE_STC3490:	/* STK 4220 1/2" cartridge */
8146 		case ST_TYPE_FUJI:	/* 1/2" cartridge */
8147 		case ST_TYPE_HP:	/* HP 88780 1/2" reel */
8148 			if (un->un_dp->type == ST_TYPE_FUJI) {
8149 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8150 				    "st_media_watch_cb: ST_TYPE_FUJI\n");
8151 			} else {
8152 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8153 				    "st_media_watch_cb: ST_TYPE_HP\n");
8154 			}
8155 			switch (sensep->es_key) {
8156 			case KEY_UNIT_ATTENTION:
8157 				/* not ready to ready transition */
8158 				/* hp/es_qual_code == 80 on>off>on */
8159 				/* hp/es_qual_code == 0 on>off>unld>ld>on */
8160 				if (sensep->es_add_code == 0x28) {
8161 					state = MTIO_INSERTED;
8162 				}
8163 				break;
8164 			case KEY_NOT_READY:
8165 				/* in process, rewinding or loading */
8166 				if ((sensep->es_add_code == 0x04) &&
8167 				    (sensep->es_qual_code == 0x00)) {
8168 					state = MTIO_EJECTED;
8169 				}
8170 				break;
8171 			}
8172 			break;
8173 
8174 		case ST_TYPE_EXB8500:	/* Exabyte 8500 */
8175 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8176 			    "st_media_watch_cb: ST_TYPE_EXB8500\n");
8177 			switch (sensep->es_key) {
8178 			case KEY_UNIT_ATTENTION:
8179 				/* operator medium removal request */
8180 				if ((sensep->es_add_code == 0x5a) &&
8181 				    (sensep->es_qual_code == 0x01)) {
8182 					state = MTIO_EJECTED;
8183 				/* not ready to ready transition */
8184 				} else if ((sensep->es_add_code == 0x28) &&
8185 				    (sensep->es_qual_code == 0x00)) {
8186 					state = MTIO_INSERTED;
8187 				}
8188 				break;
8189 			case KEY_NOT_READY:
8190 				/* medium not present */
8191 				if (sensep->es_add_code == 0x3a) {
8192 					state = MTIO_EJECTED;
8193 				}
8194 				break;
8195 			}
8196 			break;
8197 		case ST_TYPE_EXABYTE:	/* Exabyte 8200 */
8198 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8199 			    "st_media_watch_cb: ST_TYPE_EXABYTE\n");
8200 			switch (sensep->es_key) {
8201 			case KEY_NOT_READY:
8202 				if ((sensep->es_add_code == 0x04) &&
8203 				    (sensep->es_qual_code == 0x00)) {
8204 					/* volume not mounted? */
8205 					state = MTIO_EJECTED;
8206 				} else if (sensep->es_add_code == 0x3a) {
8207 					state = MTIO_EJECTED;
8208 				}
8209 				break;
8210 			case KEY_UNIT_ATTENTION:
8211 				state = MTIO_EJECTED;
8212 				break;
8213 			}
8214 			break;
8215 
8216 		case ST_TYPE_DLT:		/* quantum DLT4xxx */
8217 			switch (sensep->es_key) {
8218 			case KEY_UNIT_ATTENTION:
8219 				if (sensep->es_add_code == 0x28) {
8220 					state = MTIO_INSERTED;
8221 				}
8222 				break;
8223 			case KEY_NOT_READY:
8224 				if (sensep->es_add_code == 0x04) {
8225 					/* in transition but could be either */
8226 					state = un->un_specified_mediastate;
8227 				} else if ((sensep->es_add_code == 0x3a) &&
8228 				    (sensep->es_qual_code == 0x00)) {
8229 					state = MTIO_EJECTED;
8230 				}
8231 				break;
8232 			}
8233 			break;
8234 		}
8235 	} else if (*((char *)statusp) == STATUS_GOOD) {
8236 		state = MTIO_INSERTED;
8237 	}
8238 
8239 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8240 	    "st_media_watch_cb:state=%x, specified=%x\n",
8241 	    state, un->un_specified_mediastate);
8242 
8243 	/*
8244 	 * now signal the waiting thread if this is *not* the specified state;
8245 	 * delay the signal if the state is MTIO_INSERTED
8246 	 * to allow the target to recover
8247 	 */
8248 	if (state != un->un_specified_mediastate) {
8249 		un->un_mediastate = state;
8250 		if (state == MTIO_INSERTED) {
8251 			/*
8252 			 * delay the signal to give the drive a chance
8253 			 * to do what it apparently needs to do
8254 			 */
8255 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8256 			    "st_media_watch_cb:delayed cv_broadcast\n");
8257 			un->un_delay_tid = timeout(st_delayed_cv_broadcast,
8258 			    un, drv_usectohz((clock_t)MEDIA_ACCESS_DELAY));
8259 		} else {
8260 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8261 			    "st_media_watch_cb:immediate cv_broadcast\n");
8262 			cv_broadcast(&un->un_state_cv);
8263 		}
8264 	}
8265 	mutex_exit(ST_MUTEX);
8266 	return (0);
8267 }
8268 
8269 /*
8270  * delayed cv_broadcast to allow for target to recover
8271  * from media insertion
8272  */
8273 static void
8274 st_delayed_cv_broadcast(void *arg)
8275 {
8276 	struct scsi_tape *un = arg;
8277 
8278 	ST_FUNC(ST_DEVINFO, st_delayed_cv_broadcast);
8279 
8280 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8281 	    "st_delayed_cv_broadcast:delayed cv_broadcast\n");
8282 
8283 	mutex_enter(ST_MUTEX);
8284 	cv_broadcast(&un->un_state_cv);
8285 	mutex_exit(ST_MUTEX);
8286 }
8287 
8288 /*
8289  * restart cmd currently at the start of the waitq
8290  */
8291 static void
8292 st_start_restart(void *arg)
8293 {
8294 	struct scsi_tape *un = arg;
8295 
8296 	ST_FUNC(ST_DEVINFO, st_start_restart);
8297 
8298 	ASSERT(un != NULL);
8299 
8300 	mutex_enter(ST_MUTEX);
8301 
8302 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8303 	    "st_tran_restart()\n");
8304 
8305 	if (un->un_quef) {
8306 		st_start(un);
8307 	}
8308 
8309 	mutex_exit(ST_MUTEX);
8310 }
8311 
8312 
8313 /*
8314  * Command completion processing
8315  *
8316  */
8317 static void
8318 st_intr(struct scsi_pkt *pkt)
8319 {
8320 	struct scsi_tape *un;
8321 	struct buf *last_runqf;
8322 	struct buf *bp;
8323 	int action = COMMAND_DONE;
8324 	clock_t	timout;
8325 	int	status;
8326 
8327 
8328 	bp = pkt->pkt_private;
8329 
8330 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
8331 
8332 	ST_FUNC(ST_DEVINFO, st_intr);
8333 
8334 	mutex_enter(ST_MUTEX);
8335 
8336 	un->un_rqs_state &= ~(ST_RQS_ERROR);
8337 
8338 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_intr()\n");
8339 
8340 	if (pkt->pkt_reason != CMD_CMPLT) {
8341 
8342 		/* If device has gone away not much else to do */
8343 		if (pkt->pkt_reason == CMD_DEV_GONE) {
8344 			action = COMMAND_DONE_ERROR;
8345 		} else if (un->un_state == ST_STATE_SENSING) {
8346 			ST_DO_ERRSTATS(un, st_transerrs);
8347 			action = COMMAND_DONE_ERROR;
8348 		} else {
8349 			action = st_handle_incomplete(un, bp);
8350 		}
8351 	/*
8352 	 * At this point we know that the command was successfully
8353 	 * completed. Now what?
8354 	 */
8355 	} else if (un->un_arq_enabled &&
8356 	    (pkt->pkt_state & STATE_ARQ_DONE)) {
8357 		/*
8358 		 * the transport layer successfully completed an autorqsense
8359 		 */
8360 		action = st_handle_autosense(un, bp);
8361 
8362 	} else if (un->un_state == ST_STATE_SENSING) {
8363 		/*
8364 		 * okay. We were running a REQUEST SENSE. Find
8365 		 * out what to do next.
8366 		 * some actions are based on un_state, hence
8367 		 * restore the state st was in before ST_STATE_SENSING.
8368 		 */
8369 		un->un_state = un->un_laststate;
8370 		action = st_handle_sense(un, bp);
8371 		/*
8372 		 * set pkt back to original packet in case we will have
8373 		 * to requeue it
8374 		 */
8375 		pkt = BP_PKT(bp);
8376 	} else  if ((SCBP(pkt)->sts_busy) || (SCBP(pkt)->sts_chk)) {
8377 		/*
8378 		 * Okay, we weren't running a REQUEST SENSE. Call a routine
8379 		 * to see if the status bits we're okay. If a request sense
8380 		 * is to be run, that will happen.
8381 		 */
8382 		action = st_check_error(un, pkt);
8383 	}
8384 
8385 	if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
8386 		switch (action) {
8387 			case QUE_COMMAND:
8388 				/*
8389 				 * return cmd to head to the queue
8390 				 * since we are suspending so that
8391 				 * it gets restarted during resume
8392 				 */
8393 				if (un->un_runqf) {
8394 					last_runqf = un->un_runqf;
8395 					un->un_runqf = bp;
8396 					bp->b_actf = last_runqf;
8397 				} else {
8398 					bp->b_actf = NULL;
8399 					un->un_runqf = bp;
8400 					un->un_runql = bp;
8401 				}
8402 				action = JUST_RETURN;
8403 				break;
8404 
8405 			case QUE_SENSE:
8406 				action = COMMAND_DONE_ERROR;
8407 				break;
8408 
8409 			default:
8410 				break;
8411 		}
8412 	}
8413 
8414 	/*
8415 	 * Restore old state if we were sensing.
8416 	 */
8417 	if (un->un_state == ST_STATE_SENSING && action != QUE_SENSE) {
8418 		un->un_state = un->un_laststate;
8419 	}
8420 
8421 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8422 	    "st_intr: pkt=%p, bp=%p, action=%x, status=%x\n",
8423 	    (void *)pkt, (void *)bp, action, SCBP_C(pkt));
8424 
8425 
8426 	switch (action) {
8427 	case COMMAND_DONE_EACCES:
8428 		/* this is to report a reservation conflict */
8429 		st_bioerror(bp, EACCES);
8430 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8431 		    "Reservation Conflict \n");
8432 		un->un_pos.pmode = invalid;
8433 
8434 		/*FALLTHROUGH*/
8435 	case COMMAND_DONE_ERROR:
8436 		if (un->un_pos.eof < ST_EOT_PENDING &&
8437 		    un->un_state >= ST_STATE_OPEN) {
8438 			/*
8439 			 * all errors set state of the tape to 'unknown'
8440 			 * unless we're at EOT or are doing append testing.
8441 			 * If sense key was illegal request, preserve state.
8442 			 */
8443 			if (un->un_status != KEY_ILLEGAL_REQUEST) {
8444 				un->un_pos.pmode = invalid;
8445 			}
8446 		}
8447 
8448 		un->un_err_resid = bp->b_resid = bp->b_bcount;
8449 		/*
8450 		 * since we have an error (COMMAND_DONE_ERROR), we want to
8451 		 * make sure an error ocurrs, so make sure at least EIO is
8452 		 * returned
8453 		 */
8454 		if (geterror(bp) == 0)
8455 			st_bioerror(bp, EIO);
8456 
8457 		SET_PE_FLAG(un);
8458 		if (!(un->un_rqs_state & ST_RQS_ERROR) &&
8459 		    (un->un_errno == EIO)) {
8460 			un->un_rqs_state &= ~(ST_RQS_VALID);
8461 		}
8462 		goto done;
8463 
8464 	case COMMAND_DONE_ERROR_RECOVERED:
8465 		un->un_err_resid = bp->b_resid = bp->b_bcount;
8466 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
8467 		    "st_intr(): COMMAND_DONE_ERROR_RECOVERED");
8468 		if (geterror(bp) == 0) {
8469 			st_bioerror(bp, EIO);
8470 		}
8471 		SET_PE_FLAG(un);
8472 		if (!(un->un_rqs_state & ST_RQS_ERROR) &&
8473 		    (un->un_errno == EIO)) {
8474 			un->un_rqs_state &= ~(ST_RQS_VALID);
8475 		}
8476 		/*FALLTHROUGH*/
8477 	case COMMAND_DONE:
8478 		st_set_state(un);
8479 done:
8480 		ST_DO_KSTATS(bp, kstat_runq_exit);
8481 		st_done_and_mutex_exit(un, bp);
8482 		return;
8483 
8484 	case QUE_SENSE:
8485 		if ((un->un_ncmds > 1) && !un->un_flush_on_errors)
8486 			goto sense_error;
8487 
8488 		if (un->un_state != ST_STATE_SENSING) {
8489 			un->un_laststate = un->un_state;
8490 			un->un_state = ST_STATE_SENSING;
8491 		}
8492 
8493 		un->un_rqs->pkt_private = (opaque_t)bp;
8494 		bzero(ST_RQSENSE, SENSE_LENGTH);
8495 
8496 		if (un->un_throttle) {
8497 			un->un_last_throttle = un->un_throttle;
8498 			un->un_throttle = 0;
8499 		}
8500 
8501 		mutex_exit(ST_MUTEX);
8502 
8503 		/*
8504 		 * never retry this, some other command will have nuked the
8505 		 * sense, anyway
8506 		 */
8507 		status = scsi_transport(un->un_rqs);
8508 
8509 		mutex_enter(ST_MUTEX);
8510 
8511 		if (un->un_last_throttle) {
8512 			un->un_throttle = un->un_last_throttle;
8513 		}
8514 
8515 		if (status == TRAN_ACCEPT) {
8516 			mutex_exit(ST_MUTEX);
8517 			return;
8518 		}
8519 		if (status != TRAN_BUSY)
8520 			ST_DO_ERRSTATS(un, st_transerrs);
8521 sense_error:
8522 		un->un_pos.pmode = invalid;
8523 		st_bioerror(bp, EIO);
8524 		SET_PE_FLAG(un);
8525 		goto done;
8526 
8527 	case QUE_BUSY_COMMAND:
8528 		/* longish timeout */
8529 		timout = ST_STATUS_BUSY_TIMEOUT;
8530 		goto que_it_up;
8531 
8532 	case QUE_COMMAND:
8533 		/* short timeout */
8534 		timout = ST_TRAN_BUSY_TIMEOUT;
8535 que_it_up:
8536 		/*
8537 		 * let st_handle_intr_busy put this bp back on waitq and make
8538 		 * checks to see if it is ok to requeue the command.
8539 		 */
8540 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
8541 
8542 		/*
8543 		 * Save the throttle before setting up the timeout
8544 		 */
8545 		if (un->un_throttle) {
8546 			un->un_last_throttle = un->un_throttle;
8547 		}
8548 		mutex_exit(ST_MUTEX);
8549 		if (st_handle_intr_busy(un, bp, timout) == 0)
8550 			return;		/* timeout is setup again */
8551 
8552 		mutex_enter(ST_MUTEX);
8553 		un->un_pos.pmode = invalid;
8554 		un->un_err_resid = bp->b_resid = bp->b_bcount;
8555 		st_bioerror(bp, EIO);
8556 		SET_PE_FLAG(un);
8557 		goto done;
8558 
8559 	case QUE_LAST_COMMAND:
8560 
8561 		if ((un->un_ncmds > 1) && !un->un_flush_on_errors) {
8562 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
8563 			    "un_ncmds: %d can't retry cmd \n", un->un_ncmds);
8564 			goto last_command_error;
8565 		}
8566 		mutex_exit(ST_MUTEX);
8567 		if (st_handle_intr_retry_lcmd(un, bp) == 0)
8568 			return;
8569 		mutex_enter(ST_MUTEX);
8570 last_command_error:
8571 		un->un_err_resid = bp->b_resid = bp->b_bcount;
8572 		un->un_pos.pmode = invalid;
8573 		st_bioerror(bp, EIO);
8574 		SET_PE_FLAG(un);
8575 		goto done;
8576 
8577 	case JUST_RETURN:
8578 	default:
8579 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
8580 		mutex_exit(ST_MUTEX);
8581 		return;
8582 	}
8583 	/*NOTREACHED*/
8584 }
8585 
8586 static int
8587 st_handle_incomplete(struct scsi_tape *un, struct buf *bp)
8588 {
8589 	static char *fail = "SCSI transport failed: reason '%s': %s\n";
8590 	int rval = COMMAND_DONE_ERROR;
8591 	struct scsi_pkt *pkt = (un->un_state == ST_STATE_SENSING) ?
8592 	    un->un_rqs : BP_PKT(bp);
8593 	int result;
8594 
8595 	ST_FUNC(ST_DEVINFO, st_handle_incomplete);
8596 
8597 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8598 	    "st_handle_incomplete(): dev = 0x%lx\n", un->un_dev);
8599 
8600 	ASSERT(mutex_owned(ST_MUTEX));
8601 
8602 	switch (pkt->pkt_reason) {
8603 	case CMD_INCOMPLETE:	/* tran stopped with not normal state */
8604 		/*
8605 		 * this occurs when accessing a powered down drive, no
8606 		 * need to complain; just fail the open
8607 		 */
8608 		ST_CDB(ST_DEVINFO, "Incomplete CDB", (char *)pkt->pkt_cdbp);
8609 
8610 		/*
8611 		 * if we have commands outstanding in HBA, and a command
8612 		 * comes back incomplete, we're hosed, so reset target
8613 		 * If we have the bus, but cmd_incomplete, we probably just
8614 		 * have a failed selection, so don't reset the target, just
8615 		 * requeue the command and try again
8616 		 */
8617 		if ((un->un_ncmds > 1) || (pkt->pkt_state != STATE_GOT_BUS)) {
8618 			goto reset_target;
8619 		}
8620 
8621 		/*
8622 		 * Retry selection a couple more times if we're
8623 		 * open.  If opening, we only try just once to
8624 		 * reduce probe time for nonexistant devices.
8625 		 */
8626 		if ((un->un_laststate > ST_STATE_OPENING) &&
8627 		    ((int)un->un_retry_ct < st_selection_retry_count)) {
8628 			rval = QUE_COMMAND;
8629 		}
8630 		ST_DO_ERRSTATS(un, st_transerrs);
8631 		break;
8632 
8633 	case CMD_ABORTED:
8634 		/*
8635 		 * most likely this is caused by flush-on-error support. If
8636 		 * it was not there, the we're in trouble.
8637 		 */
8638 		if (!un->un_flush_on_errors) {
8639 			un->un_status = SUN_KEY_FATAL;
8640 			goto reset_target;
8641 		}
8642 
8643 		st_set_pe_errno(un);
8644 		bioerror(bp, un->un_errno);
8645 		if (un->un_errno)
8646 			return (COMMAND_DONE_ERROR);
8647 		else
8648 			return (COMMAND_DONE);
8649 
8650 	case CMD_TIMEOUT:	/* Command timed out */
8651 		un->un_status = SUN_KEY_TIMEOUT;
8652 
8653 		/*FALLTHROUGH*/
8654 	default:
8655 reset_target:
8656 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
8657 		    "transport completed with %s\n",
8658 		    scsi_rname(pkt->pkt_reason));
8659 		ST_DO_ERRSTATS(un, st_transerrs);
8660 		if ((pkt->pkt_state & STATE_GOT_TARGET) &&
8661 		    ((pkt->pkt_statistics & (STAT_BUS_RESET | STAT_DEV_RESET |
8662 		    STAT_ABORTED)) == 0)) {
8663 
8664 			/*
8665 			 * If we haven't reserved the drive don't reset it.
8666 			 */
8667 			if ((un->un_rsvd_status &
8668 			    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
8669 				return (rval);
8670 			}
8671 
8672 			/*
8673 			 * if we aren't lost yet we will be soon.
8674 			 */
8675 			un->un_pos.pmode = invalid;
8676 
8677 			mutex_exit(ST_MUTEX);
8678 
8679 			result = scsi_reset(ROUTE, RESET_TARGET);
8680 			/*
8681 			 * if target reset fails, then pull the chain
8682 			 */
8683 			if (result == 0) {
8684 				result = scsi_reset(ROUTE, RESET_ALL);
8685 			}
8686 			mutex_enter(ST_MUTEX);
8687 
8688 			if ((result == 0) && (un->un_state >= ST_STATE_OPEN)) {
8689 				/* no hope left to recover */
8690 				scsi_log(ST_DEVINFO, st_label, CE_WARN,
8691 				    "recovery by resets failed\n");
8692 				return (rval);
8693 			}
8694 		}
8695 	}
8696 
8697 	if ((pkt->pkt_reason == CMD_RESET) || (pkt->pkt_statistics &
8698 	    (STAT_BUS_RESET | STAT_DEV_RESET))) {
8699 		if ((un->un_rsvd_status & ST_RESERVE)) {
8700 			un->un_rsvd_status |= ST_LOST_RESERVE;
8701 			ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
8702 			    "Lost Reservation\n");
8703 		}
8704 	}
8705 
8706 	if ((int)un->un_retry_ct++ < st_retry_count) {
8707 		if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
8708 			rval = QUE_COMMAND;
8709 		} else if (bp == un->un_sbufp) {
8710 			switch ((uchar_t)(uintptr_t)bp->b_forw) {
8711 			case SCMD_MODE_SENSE:
8712 			case SCMD_MODE_SELECT:
8713 			case SCMD_READ_BLKLIM:
8714 			case SCMD_REWIND:
8715 			case SCMD_LOAD:
8716 			case SCMD_TEST_UNIT_READY:
8717 				/*
8718 				 * These commands can be rerun with impunity
8719 				 */
8720 				rval = QUE_COMMAND;
8721 				break;
8722 
8723 			default:
8724 				break;
8725 			}
8726 		}
8727 	} else {
8728 		rval = COMMAND_DONE_ERROR;
8729 	}
8730 
8731 	if (un->un_state >= ST_STATE_OPEN) {
8732 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
8733 		    fail, scsi_rname(pkt->pkt_reason),
8734 		    (rval == COMMAND_DONE_ERROR)?
8735 		    "giving up" : "retrying command");
8736 	}
8737 	return (rval);
8738 }
8739 
8740 /*
8741  * if the device is busy, then put this bp back on the waitq, on the
8742  * interrupt thread, where we want the head of the queue and not the
8743  * end
8744  *
8745  * The callers of this routine should take measures to save the
8746  * un_throttle in un_last_throttle which will be restored in
8747  * st_intr_restart(). The only exception should be st_intr_restart()
8748  * calling this routine for which the saving is already done.
8749  */
8750 static int
8751 st_handle_intr_busy(struct scsi_tape *un, struct buf *bp,
8752 	clock_t timeout_interval)
8753 {
8754 	struct buf *last_quef;
8755 	int rval = 0;
8756 
8757 	mutex_enter(ST_MUTEX);
8758 
8759 	ST_FUNC(ST_DEVINFO, st_handle_intr_busy);
8760 
8761 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8762 	    "st_handle_intr_busy(), un = 0x%p\n", (void *)un);
8763 
8764 	/*
8765 	 * Check to see if we hit the retry timeout. We check to make sure
8766 	 * this is the first one on the runq and make sure we have not
8767 	 * queued up any more, so this one has to be the last on the list
8768 	 * also. If it is not, we have to fail.  If it is not the first, but
8769 	 * is the last we are in trouble anyway, as we are in the interrupt
8770 	 * context here.
8771 	 */
8772 	if (((int)un->un_tran_retry_ct++ > st_retry_count) ||
8773 	    ((un->un_runqf != bp) && (un->un_runql != bp))) {
8774 		rval = -1;
8775 		goto exit;
8776 	}
8777 
8778 	/* put the bp back on the waitq */
8779 	if (un->un_quef) {
8780 		last_quef = un->un_quef;
8781 		un->un_quef = bp;
8782 		bp->b_actf = last_quef;
8783 	} else  {
8784 		bp->b_actf = NULL;
8785 		un->un_quef = bp;
8786 		un->un_quel = bp;
8787 	}
8788 
8789 	/*
8790 	 * We know that this is the first and last on the runq at this time,
8791 	 * so we just nullify those two queues
8792 	 */
8793 	un->un_runqf = NULL;
8794 	un->un_runql = NULL;
8795 
8796 	/*
8797 	 * We don't want any other commands being started in the mean time.
8798 	 * If start had just released mutex after putting something on the
8799 	 * runq, we won't even get here.
8800 	 */
8801 	un->un_throttle = 0;
8802 
8803 	/*
8804 	 * send a marker pkt, if appropriate
8805 	 */
8806 	st_hba_unflush(un);
8807 
8808 	/*
8809 	 * all queues are aligned, we are just waiting to
8810 	 * transport
8811 	 */
8812 	un->un_hib_tid = timeout(st_intr_restart, un, timeout_interval);
8813 
8814 exit:
8815 	mutex_exit(ST_MUTEX);
8816 	return (rval);
8817 }
8818 
8819 static int
8820 st_handle_sense(struct scsi_tape *un, struct buf *bp)
8821 {
8822 	struct scsi_pkt *rqpkt = un->un_rqs;
8823 	int rval = COMMAND_DONE_ERROR;
8824 	int amt;
8825 
8826 	ST_FUNC(ST_DEVINFO, st_handle_sense);
8827 
8828 	ASSERT(mutex_owned(ST_MUTEX));
8829 
8830 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8831 	    "st_handle_sense()\n");
8832 
8833 	if (SCBP(rqpkt)->sts_busy) {
8834 		ST_DEBUG4(ST_DEVINFO, st_label, CE_WARN,
8835 		    "busy unit on request sense\n");
8836 		if ((int)un->un_retry_ct++ < st_retry_count) {
8837 			rval = QUE_BUSY_COMMAND;
8838 		}
8839 		return (rval);
8840 	} else if (SCBP(rqpkt)->sts_chk) {
8841 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
8842 		    "Check Condition on REQUEST SENSE\n");
8843 		return (rval);
8844 	}
8845 
8846 	/* was there enough data? */
8847 	amt = (int)SENSE_LENGTH - rqpkt->pkt_resid;
8848 	if ((rqpkt->pkt_state & STATE_XFERRED_DATA) == 0 ||
8849 	    (amt < SUN_MIN_SENSE_LENGTH)) {
8850 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
8851 		    "REQUEST SENSE couldn't get sense data\n");
8852 		return (rval);
8853 	}
8854 	return (st_decode_sense(un, bp, amt, SCBP(rqpkt)));
8855 }
8856 
8857 static int
8858 st_handle_autosense(struct scsi_tape *un, struct buf *bp)
8859 {
8860 	struct scsi_pkt *pkt = BP_PKT(bp);
8861 	struct scsi_arq_status *arqstat =
8862 	    (struct scsi_arq_status *)pkt->pkt_scbp;
8863 	int rval = COMMAND_DONE_ERROR;
8864 	int amt;
8865 
8866 	ST_FUNC(ST_DEVINFO, st_handle_autosense);
8867 
8868 	ASSERT(mutex_owned(ST_MUTEX));
8869 
8870 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8871 	    "st_handle_autosense()\n");
8872 
8873 	if (arqstat->sts_rqpkt_status.sts_busy) {
8874 		ST_DEBUG4(ST_DEVINFO, st_label, CE_WARN,
8875 		    "busy unit on request sense\n");
8876 		/*
8877 		 * we return QUE_SENSE so st_intr will setup the SENSE cmd.
8878 		 * the disadvantage is that we do not have any delay for the
8879 		 * second retry of rqsense and we have to keep a packet around
8880 		 */
8881 		return (QUE_SENSE);
8882 
8883 	} else if (arqstat->sts_rqpkt_reason != CMD_CMPLT) {
8884 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
8885 		    "transport error on REQUEST SENSE\n");
8886 		if ((arqstat->sts_rqpkt_state & STATE_GOT_TARGET) &&
8887 		    ((arqstat->sts_rqpkt_statistics &
8888 		    (STAT_BUS_RESET | STAT_DEV_RESET | STAT_ABORTED)) == 0)) {
8889 			mutex_exit(ST_MUTEX);
8890 			if (scsi_reset(ROUTE, RESET_TARGET) == 0) {
8891 				/*
8892 				 * if target reset fails, then pull the chain
8893 				 */
8894 				if (scsi_reset(ROUTE, RESET_ALL) == 0) {
8895 					ST_DEBUG6(ST_DEVINFO, st_label,
8896 					    CE_WARN,
8897 					    "recovery by resets failed\n");
8898 				}
8899 			}
8900 			mutex_enter(ST_MUTEX);
8901 		}
8902 		return (rval);
8903 
8904 	} else if (arqstat->sts_rqpkt_status.sts_chk) {
8905 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
8906 		    "Check Condition on REQUEST SENSE\n");
8907 		return (rval);
8908 	}
8909 
8910 
8911 	/* was there enough data? */
8912 	amt = (int)SENSE_LENGTH - arqstat->sts_rqpkt_resid;
8913 	if ((arqstat->sts_rqpkt_state & STATE_XFERRED_DATA) == 0 ||
8914 	    (amt < SUN_MIN_SENSE_LENGTH)) {
8915 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
8916 		    "REQUEST SENSE couldn't get sense data\n");
8917 		return (rval);
8918 	}
8919 
8920 	bcopy(&arqstat->sts_sensedata, ST_RQSENSE, SENSE_LENGTH);
8921 
8922 	return (st_decode_sense(un, bp, amt, &arqstat->sts_rqpkt_status));
8923 }
8924 
8925 static int
8926 st_decode_sense(struct scsi_tape *un, struct buf *bp,  int amt,
8927 	struct scsi_status *statusp)
8928 {
8929 	struct scsi_pkt *pkt = BP_PKT(bp);
8930 	int rval = COMMAND_DONE_ERROR;
8931 	long resid;
8932 	struct scsi_extended_sense *sensep = ST_RQSENSE;
8933 	int severity;
8934 	int get_error;
8935 
8936 	ST_FUNC(ST_DEVINFO, st_decode_sense);
8937 
8938 	ASSERT(mutex_owned(ST_MUTEX));
8939 
8940 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8941 	    "st_decode_sense()\n");
8942 
8943 	/*
8944 	 * For uscsi commands, squirrel away a copy of the
8945 	 * results of the Request Sense.
8946 	 */
8947 	if (USCSI_CMD(bp)) {
8948 		struct uscsi_cmd *ucmd = BP_UCMD(bp);
8949 		ucmd->uscsi_rqstatus = *(uchar_t *)statusp;
8950 		if (ucmd->uscsi_rqlen && un->un_srqbufp) {
8951 			uchar_t rqlen = min((uchar_t)amt, ucmd->uscsi_rqlen);
8952 			ucmd->uscsi_rqresid = ucmd->uscsi_rqlen - rqlen;
8953 			bcopy(ST_RQSENSE, un->un_srqbufp, rqlen);
8954 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8955 			    "st_decode_sense: stat=0x%x resid=0x%x\n",
8956 			    ucmd->uscsi_rqstatus, ucmd->uscsi_rqresid);
8957 		}
8958 	}
8959 
8960 	/*
8961 	 * If the drive is an MT-02, reposition the
8962 	 * secondary error code into the proper place.
8963 	 *
8964 	 * XXX	MT-02 is non-CCS tape, so secondary error code
8965 	 * is in byte 8.  However, in SCSI-2, tape has CCS definition
8966 	 * so it's in byte 12.
8967 	 */
8968 	if (un->un_dp->type == ST_TYPE_EMULEX) {
8969 		sensep->es_code = sensep->es_add_info[0];
8970 	}
8971 
8972 	ST_CDB(ST_DEVINFO, "st_decode_sense failed CDB",
8973 	    (caddr_t)&CDBP(pkt)->scc_cmd);
8974 
8975 	ST_SENSE(ST_DEVINFO, "st_decode_sense sense data", (caddr_t)sensep,
8976 	    sizeof (*sensep));
8977 
8978 	/* for normal I/O check extract the resid values. */
8979 	if (bp != un->un_sbufp) {
8980 		if (sensep->es_valid) {
8981 			resid =
8982 			    (sensep->es_info_1 << 24) |
8983 			    (sensep->es_info_2 << 16) |
8984 			    (sensep->es_info_3 << 8)  |
8985 			    (sensep->es_info_4);
8986 			/* If fixed block */
8987 			if (un->un_bsize) {
8988 				resid *= un->un_bsize;
8989 			}
8990 		} else if (pkt->pkt_state & STATE_XFERRED_DATA) {
8991 			resid = pkt->pkt_resid;
8992 		} else {
8993 			resid = bp->b_bcount;
8994 		}
8995 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8996 		    "st_handle_sense (rw): xferred bit = %d, resid=%ld (%d), "
8997 		    "pkt_resid=%ld\n", pkt->pkt_state & STATE_XFERRED_DATA,
8998 		    resid,
8999 		    (sensep->es_info_1 << 24) |
9000 		    (sensep->es_info_2 << 16) |
9001 		    (sensep->es_info_3 << 8)  |
9002 		    (sensep->es_info_4),
9003 		    pkt->pkt_resid);
9004 		/*
9005 		 * The problem is, what should we believe?
9006 		 */
9007 		if (resid && (pkt->pkt_resid == 0)) {
9008 			pkt->pkt_resid = resid;
9009 		}
9010 	} else {
9011 		/*
9012 		 * If the command is SCMD_SPACE, we need to get the
9013 		 * residual as returned in the sense data, to adjust
9014 		 * our idea of current tape position correctly
9015 		 */
9016 		if ((CDBP(pkt)->scc_cmd == SCMD_LOCATE) ||
9017 		    (CDBP(pkt)->scc_cmd == SCMD_LOCATE_G4) ||
9018 		    (CDBP(pkt)->scc_cmd == SCMD_SPACE) ||
9019 		    (CDBP(pkt)->scc_cmd == SCMD_WRITE_FILE_MARK) &&
9020 		    (sensep->es_valid)) {
9021 			resid =
9022 			    (sensep->es_info_1 << 24) |
9023 			    (sensep->es_info_2 << 16) |
9024 			    (sensep->es_info_3 << 8)  |
9025 			    (sensep->es_info_4);
9026 			bp->b_resid = resid;
9027 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9028 			    "st_handle_sense(other):	resid=%ld\n", resid);
9029 		} else {
9030 			/*
9031 			 * If the special command is SCMD_READ,
9032 			 * the correct resid will be set later.
9033 			 */
9034 			resid = bp->b_bcount;
9035 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9036 			    "st_handle_sense(special read):  resid=%ld\n",
9037 			    resid);
9038 		}
9039 	}
9040 
9041 	if ((un->un_state >= ST_STATE_OPEN) &&
9042 	    (DEBUGGING || st_error_level == SCSI_ERR_ALL)) {
9043 		st_print_cdb(ST_DEVINFO, st_label, CE_NOTE,
9044 		    "Failed CDB", (char *)pkt->pkt_cdbp);
9045 		st_clean_print(ST_DEVINFO, st_label, CE_CONT,
9046 		    "sense data", (char *)sensep, amt);
9047 		scsi_log(ST_DEVINFO, st_label, CE_CONT,
9048 		    "count 0x%lx resid 0x%lx pktresid 0x%lx\n",
9049 		    bp->b_bcount, resid, pkt->pkt_resid);
9050 	}
9051 
9052 	switch (un->un_status = sensep->es_key) {
9053 	case KEY_NO_SENSE:
9054 		severity = SCSI_ERR_INFO;
9055 
9056 		/*
9057 		 * Erase, locate or rewind operation in progress, retry
9058 		 * ASC  ASCQ
9059 		 *  00   18    Erase operation in progress
9060 		 *  00   19    Locate operation in progress
9061 		 *  00   1A    Rewind operation in progress
9062 		 */
9063 		if (sensep->es_add_code == 0 &&
9064 		    ((sensep->es_qual_code == 0x18) ||
9065 		    (sensep->es_qual_code == 0x19) ||
9066 		    (sensep->es_qual_code == 0x1a))) {
9067 			rval = QUE_COMMAND;
9068 			break;
9069 		}
9070 
9071 		goto common;
9072 
9073 	case KEY_RECOVERABLE_ERROR:
9074 		severity = SCSI_ERR_RECOVERED;
9075 		if ((sensep->es_class == CLASS_EXTENDED_SENSE) &&
9076 		    (sensep->es_code == ST_DEFERRED_ERROR)) {
9077 			if (un->un_dp->options &
9078 			    ST_RETRY_ON_RECOVERED_DEFERRED_ERROR) {
9079 				rval = QUE_LAST_COMMAND;
9080 				scsi_errmsg(ST_SCSI_DEVP, pkt, st_label,
9081 				    severity, un->un_pos.lgclblkno,
9082 				    un->un_err_pos.lgclblkno, scsi_cmds,
9083 				    sensep);
9084 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
9085 				    "Command will be retried\n");
9086 			} else {
9087 				severity = SCSI_ERR_FATAL;
9088 				rval = COMMAND_DONE_ERROR_RECOVERED;
9089 				ST_DO_ERRSTATS(un, st_softerrs);
9090 				scsi_errmsg(ST_SCSI_DEVP, pkt, st_label,
9091 				    severity, un->un_pos.lgclblkno,
9092 				    un->un_err_pos.lgclblkno, scsi_cmds,
9093 				    sensep);
9094 			}
9095 			break;
9096 		}
9097 common:
9098 		/*
9099 		 * XXX only want reads to be stopped by filemarks.
9100 		 * Don't want them to be stopped by EOT.  EOT matters
9101 		 * only on write.
9102 		 */
9103 		if (sensep->es_filmk && !sensep->es_eom) {
9104 			rval = COMMAND_DONE;
9105 		} else if (sensep->es_eom) {
9106 			rval = COMMAND_DONE;
9107 		} else if (sensep->es_ili) {
9108 			/*
9109 			 * Fun with variable length record devices:
9110 			 * for specifying larger blocks sizes than the
9111 			 * actual physical record size.
9112 			 */
9113 			if (un->un_bsize == 0 && resid > 0) {
9114 				/*
9115 				 * XXX! Ugly.
9116 				 * The requested blocksize is > tape blocksize,
9117 				 * so this is ok, so we just return the
9118 				 * actual size xferred.
9119 				 */
9120 				pkt->pkt_resid = resid;
9121 				rval = COMMAND_DONE;
9122 			} else if (un->un_bsize == 0 && resid < 0) {
9123 				/*
9124 				 * The requested blocksize is < tape blocksize,
9125 				 * so this is not ok, so we err with ENOMEM
9126 				 */
9127 				rval = COMMAND_DONE_ERROR_RECOVERED;
9128 				st_bioerror(bp, ENOMEM);
9129 			} else {
9130 				ST_DO_ERRSTATS(un, st_softerrs);
9131 				severity = SCSI_ERR_FATAL;
9132 				rval = COMMAND_DONE_ERROR;
9133 				st_bioerror(bp, EINVAL);
9134 			}
9135 		} else {
9136 			/*
9137 			 * we hope and pray for this just being
9138 			 * something we can ignore (ie. a
9139 			 * truly recoverable soft error)
9140 			 */
9141 			rval = COMMAND_DONE;
9142 		}
9143 		if (sensep->es_filmk) {
9144 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9145 			    "filemark\n");
9146 			un->un_status = SUN_KEY_EOF;
9147 			un->un_pos.eof = ST_EOF_PENDING;
9148 			SET_PE_FLAG(un);
9149 		}
9150 
9151 		/*
9152 		 * ignore eom when reading, a fmk should terminate reading
9153 		 */
9154 		if ((sensep->es_eom) &&
9155 		    (CDBP(pkt)->scc_cmd != SCMD_READ)) {
9156 			if ((sensep->es_add_code == 0) &&
9157 			    (sensep->es_qual_code == 4)) {
9158 				ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9159 				    "bot\n");
9160 				un->un_status = SUN_KEY_BOT;
9161 				un->un_pos.eof = ST_NO_EOF;
9162 				un->un_pos.lgclblkno = 0;
9163 				un->un_pos.fileno = 0;
9164 				un->un_pos.blkno = 0;
9165 				un->un_pos.pmode = legacy;
9166 			} else {
9167 				ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9168 				    "eom\n");
9169 				un->un_status = SUN_KEY_EOT;
9170 				un->un_pos.eof = ST_EOM;
9171 			}
9172 			SET_PE_FLAG(un);
9173 		}
9174 
9175 		break;
9176 
9177 	case KEY_ILLEGAL_REQUEST:
9178 
9179 		if (un->un_laststate >= ST_STATE_OPEN) {
9180 			ST_DO_ERRSTATS(un, st_softerrs);
9181 			severity = SCSI_ERR_FATAL;
9182 		} else {
9183 			severity = SCSI_ERR_INFO;
9184 		}
9185 		break;
9186 
9187 	case KEY_MEDIUM_ERROR:
9188 		ST_DO_ERRSTATS(un, st_harderrs);
9189 		severity = SCSI_ERR_FATAL;
9190 
9191 		/*
9192 		 * for (buffered) writes, a medium error must be fatal
9193 		 */
9194 		if (CDBP(pkt)->scc_cmd != SCMD_WRITE) {
9195 			rval = COMMAND_DONE_ERROR_RECOVERED;
9196 		}
9197 
9198 check_keys:
9199 		/*
9200 		 * attempt to process the keys in the presence of
9201 		 * other errors
9202 		 */
9203 		if (sensep->es_ili && rval != COMMAND_DONE_ERROR) {
9204 			/*
9205 			 * Fun with variable length record devices:
9206 			 * for specifying larger blocks sizes than the
9207 			 * actual physical record size.
9208 			 */
9209 			if (un->un_bsize == 0 && resid > 0) {
9210 				/*
9211 				 * XXX! Ugly
9212 				 */
9213 				pkt->pkt_resid = resid;
9214 			} else if (un->un_bsize == 0 && resid < 0) {
9215 				st_bioerror(bp, EINVAL);
9216 			} else {
9217 				severity = SCSI_ERR_FATAL;
9218 				rval = COMMAND_DONE_ERROR;
9219 				st_bioerror(bp, EINVAL);
9220 			}
9221 		}
9222 		if (sensep->es_filmk) {
9223 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9224 			    "filemark\n");
9225 			un->un_status = SUN_KEY_EOF;
9226 			un->un_pos.eof = ST_EOF_PENDING;
9227 			SET_PE_FLAG(un);
9228 		}
9229 
9230 		/*
9231 		 * ignore eom when reading, a fmk should terminate reading
9232 		 */
9233 		if ((sensep->es_eom) &&
9234 		    (CDBP(pkt)->scc_cmd != SCMD_READ)) {
9235 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "eom\n");
9236 			un->un_status = SUN_KEY_EOT;
9237 			un->un_pos.eof = ST_EOM;
9238 			SET_PE_FLAG(un);
9239 		}
9240 
9241 		break;
9242 
9243 	case KEY_VOLUME_OVERFLOW:
9244 		ST_DO_ERRSTATS(un, st_softerrs);
9245 		un->un_pos.eof = ST_EOM;
9246 		severity = SCSI_ERR_FATAL;
9247 		rval = COMMAND_DONE_ERROR;
9248 		goto check_keys;
9249 
9250 	case KEY_HARDWARE_ERROR:
9251 		ST_DO_ERRSTATS(un, st_harderrs);
9252 		severity = SCSI_ERR_FATAL;
9253 		rval = COMMAND_DONE_ERROR;
9254 		if (un->un_dp->options & ST_EJECT_ON_CHANGER_FAILURE)
9255 			un->un_eject_tape_on_failure = st_check_asc_ascq(un);
9256 		break;
9257 
9258 	case KEY_BLANK_CHECK:
9259 		ST_DO_ERRSTATS(un, st_softerrs);
9260 		severity = SCSI_ERR_INFO;
9261 
9262 		/*
9263 		 * if not a special request and some data was xferred then it
9264 		 * it is not an error yet
9265 		 */
9266 		if (bp != un->un_sbufp && (bp->b_flags & B_READ)) {
9267 			/*
9268 			 * no error for read with or without data xferred
9269 			 */
9270 			un->un_status = SUN_KEY_EOT;
9271 			un->un_pos.eof = ST_EOT;
9272 			rval = COMMAND_DONE_ERROR;
9273 			SET_PE_FLAG(un);
9274 			goto check_keys;
9275 		} else if (bp != un->un_sbufp &&
9276 		    (pkt->pkt_state & STATE_XFERRED_DATA)) {
9277 			rval = COMMAND_DONE;
9278 		} else {
9279 			rval = COMMAND_DONE_ERROR_RECOVERED;
9280 		}
9281 
9282 		if (un->un_laststate >= ST_STATE_OPEN) {
9283 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9284 			    "blank check\n");
9285 			un->un_pos.eof = ST_EOM;
9286 		}
9287 		if ((CDBP(pkt)->scc_cmd == SCMD_LOCATE) ||
9288 		    (CDBP(pkt)->scc_cmd == SCMD_LOCATE_G4) ||
9289 		    (CDBP(pkt)->scc_cmd == SCMD_SPACE) &&
9290 		    (un->un_dp->options & ST_KNOWS_EOD)) {
9291 			/*
9292 			 * we were doing a fast forward by skipping
9293 			 * multiple fmk at the time
9294 			 */
9295 			st_bioerror(bp, EIO);
9296 			severity = SCSI_ERR_RECOVERED;
9297 			rval	 = COMMAND_DONE;
9298 		}
9299 		SET_PE_FLAG(un);
9300 		goto check_keys;
9301 
9302 	case KEY_WRITE_PROTECT:
9303 		if (st_wrongtapetype(un)) {
9304 			un->un_status = SUN_KEY_WRONGMEDIA;
9305 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9306 		"wrong tape for writing- use DC6150 tape (or equivalent)\n");
9307 			severity = SCSI_ERR_UNKNOWN;
9308 		} else {
9309 			severity = SCSI_ERR_FATAL;
9310 		}
9311 		ST_DO_ERRSTATS(un, st_harderrs);
9312 		rval = COMMAND_DONE_ERROR;
9313 		st_bioerror(bp, EACCES);
9314 		break;
9315 
9316 	case KEY_UNIT_ATTENTION:
9317 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9318 		    "KEY_UNIT_ATTENTION : un_state = %d\n", un->un_state);
9319 
9320 		/*
9321 		 * If we have detected a Bus Reset and the tape
9322 		 * drive has been reserved.
9323 		 */
9324 		if (ST_RQSENSE->es_add_code == 0x29 &&
9325 		    (un->un_rsvd_status & ST_RESERVE)) {
9326 			un->un_rsvd_status |= ST_LOST_RESERVE;
9327 			ST_DEBUG(ST_DEVINFO, st_label, CE_WARN,
9328 			    "st_decode_sense: Lost Reservation\n");
9329 		}
9330 
9331 		if (un->un_state <= ST_STATE_OPENING) {
9332 			/*
9333 			 * Look, the tape isn't open yet, now determine
9334 			 * if the cause is a BUS RESET, Save the file and
9335 			 * Block positions for the callers to recover from
9336 			 * the loss of position.
9337 			 */
9338 			if (un->un_pos.pmode != invalid) {
9339 				if (ST_RQSENSE->es_add_code == 0x29) {
9340 					un->un_save_fileno = un->un_pos.fileno;
9341 					un->un_save_blkno = un->un_pos.blkno;
9342 					un->un_restore_pos = 1;
9343 				}
9344 			}
9345 
9346 			if ((int)un->un_retry_ct++ < st_retry_count) {
9347 				rval = QUE_COMMAND;
9348 			} else {
9349 				rval = COMMAND_DONE_ERROR;
9350 			}
9351 			severity = SCSI_ERR_INFO;
9352 
9353 		} else {
9354 			/*
9355 			 * Check if it is an Unexpected Unit Attention.
9356 			 * If state is >= ST_STATE_OPEN, we have
9357 			 * already done the initialization .
9358 			 * In this case it is Fatal Error
9359 			 * since no further reading/writing
9360 			 * can be done with fileno set to < 0.
9361 			 */
9362 			if (un->un_state >= ST_STATE_OPEN) {
9363 				ST_DO_ERRSTATS(un, st_harderrs);
9364 				severity = SCSI_ERR_FATAL;
9365 			} else {
9366 				severity = SCSI_ERR_INFO;
9367 			}
9368 			rval = COMMAND_DONE_ERROR;
9369 		}
9370 		un->un_pos.pmode = invalid;
9371 
9372 		break;
9373 
9374 	case KEY_NOT_READY:
9375 		/*
9376 		 * If in process of getting ready retry.
9377 		 */
9378 		if (sensep->es_add_code  == 0x04 &&
9379 		    sensep->es_qual_code == 0x01 &&
9380 		    un->un_retry_ct++ < st_retry_count) {
9381 			rval = QUE_COMMAND;
9382 			severity = SCSI_ERR_INFO;
9383 		} else {
9384 			/* give up */
9385 			rval = COMMAND_DONE_ERROR;
9386 			severity = SCSI_ERR_FATAL;
9387 		}
9388 
9389 		/*
9390 		 * If this was an error and after device opened
9391 		 * do error stats.
9392 		 */
9393 		if (rval == COMMAND_DONE_ERROR &&
9394 		    un->un_state > ST_STATE_OPENING) {
9395 			ST_DO_ERRSTATS(un, st_harderrs);
9396 		}
9397 
9398 		if (ST_RQSENSE->es_add_code == 0x3a) {
9399 			if (st_error_level >= SCSI_ERR_FATAL)
9400 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
9401 				    "Tape not inserted in drive\n");
9402 			un->un_mediastate = MTIO_EJECTED;
9403 			cv_broadcast(&un->un_state_cv);
9404 		}
9405 		if ((un->un_dp->options & ST_EJECT_ON_CHANGER_FAILURE) &&
9406 		    (rval != QUE_COMMAND))
9407 			un->un_eject_tape_on_failure = st_check_asc_ascq(un);
9408 		break;
9409 
9410 	case KEY_ABORTED_COMMAND:
9411 
9412 		/*
9413 		 * Probably a parity error...
9414 		 * if we retry here then this may cause data to be
9415 		 * written twice or data skipped during reading
9416 		 */
9417 		ST_DO_ERRSTATS(un, st_harderrs);
9418 		severity = SCSI_ERR_FATAL;
9419 		rval = COMMAND_DONE_ERROR;
9420 		goto check_keys;
9421 
9422 	default:
9423 		/*
9424 		 * Undecoded sense key.	 Try retries and hope
9425 		 * that will fix the problem.  Otherwise, we're
9426 		 * dead.
9427 		 */
9428 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9429 		    "Unhandled Sense Key '%s'\n",
9430 		    sense_keys[un->un_status]);
9431 		ST_DO_ERRSTATS(un, st_harderrs);
9432 		severity = SCSI_ERR_FATAL;
9433 		rval = COMMAND_DONE_ERROR;
9434 		goto check_keys;
9435 	}
9436 
9437 	if ((!(pkt->pkt_flags & FLAG_SILENT) &&
9438 	    un->un_state >= ST_STATE_OPEN) && (DEBUGGING ||
9439 	    (un->un_laststate > ST_STATE_OPENING) &&
9440 	    (severity >= st_error_level))) {
9441 
9442 		scsi_errmsg(ST_SCSI_DEVP, pkt, st_label, severity,
9443 		    un->un_pos.lgclblkno, un->un_err_pos.lgclblkno,
9444 		    scsi_cmds, sensep);
9445 		if (sensep->es_filmk) {
9446 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
9447 			    "File Mark Detected\n");
9448 		}
9449 		if (sensep->es_eom) {
9450 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
9451 			    "End-of-Media Detected\n");
9452 		}
9453 		if (sensep->es_ili) {
9454 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
9455 			    "Incorrect Length Indicator Set\n");
9456 		}
9457 	}
9458 	get_error = geterror(bp);
9459 	if (((rval == COMMAND_DONE_ERROR) ||
9460 	    (rval == COMMAND_DONE_ERROR_RECOVERED)) &&
9461 	    ((get_error == EIO) || (get_error == 0))) {
9462 		un->un_rqs_state |= (ST_RQS_ERROR | ST_RQS_VALID);
9463 		bcopy(ST_RQSENSE, un->un_uscsi_rqs_buf, SENSE_LENGTH);
9464 		if (un->un_rqs_state & ST_RQS_READ) {
9465 			un->un_rqs_state &= ~(ST_RQS_READ);
9466 		} else {
9467 			un->un_rqs_state |= ST_RQS_OVR;
9468 		}
9469 	}
9470 
9471 	return (rval);
9472 }
9473 
9474 
9475 static int
9476 st_handle_intr_retry_lcmd(struct scsi_tape *un, struct buf *bp)
9477 {
9478 	int status = TRAN_ACCEPT;
9479 
9480 	mutex_enter(ST_MUTEX);
9481 
9482 	ST_FUNC(ST_DEVINFO, st_handle_intr_retry_lcmd);
9483 
9484 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9485 	    "st_handle_intr_rtr_lcmd(), un = 0x%p\n", (void *)un);
9486 
9487 	/*
9488 	 * Check to see if we hit the retry timeout. We check to make sure
9489 	 * this is the first one on the runq and make sure we have not
9490 	 * queued up any more, so this one has to be the last on the list
9491 	 * also. If it is not, we have to fail.  If it is not the first, but
9492 	 * is the last we are in trouble anyway, as we are in the interrupt
9493 	 * context here.
9494 	 */
9495 	if (((int)un->un_retry_ct > st_retry_count) ||
9496 	    ((un->un_runqf != bp) && (un->un_runql != bp))) {
9497 		goto exit;
9498 	}
9499 
9500 	if (un->un_throttle) {
9501 		un->un_last_throttle = un->un_throttle;
9502 		un->un_throttle = 0;
9503 	}
9504 
9505 	/*
9506 	 * Here we know : bp is the first and last one on the runq
9507 	 * it is not necessary to put it back on the head of the
9508 	 * waitq and then move from waitq to runq. Save this queuing
9509 	 * and call scsi_transport.
9510 	 */
9511 
9512 	mutex_exit(ST_MUTEX);
9513 
9514 	status = scsi_transport(BP_PKT(bp));
9515 
9516 	mutex_enter(ST_MUTEX);
9517 
9518 	if (status == TRAN_ACCEPT) {
9519 		un->un_tran_retry_ct = 0;
9520 		if (un->un_last_throttle) {
9521 			un->un_throttle = un->un_last_throttle;
9522 		}
9523 		mutex_exit(ST_MUTEX);
9524 
9525 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9526 		    "restart transport \n");
9527 		return (0);
9528 	}
9529 
9530 	ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
9531 	mutex_exit(ST_MUTEX);
9532 
9533 	if (status == TRAN_BUSY) {
9534 		if (st_handle_intr_busy(un, bp, ST_TRAN_BUSY_TIMEOUT) == 0) {
9535 			return (0);
9536 		}
9537 	}
9538 	ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9539 	    "restart transport rejected\n");
9540 	mutex_enter(ST_MUTEX);
9541 	ST_DO_ERRSTATS(un, st_transerrs);
9542 	if (un->un_last_throttle) {
9543 		un->un_throttle = un->un_last_throttle;
9544 	}
9545 exit:
9546 	mutex_exit(ST_MUTEX);
9547 	return (-1);
9548 }
9549 
9550 static int
9551 st_wrongtapetype(struct scsi_tape *un)
9552 {
9553 
9554 	ST_FUNC(ST_DEVINFO, st_wrongtapetype);
9555 
9556 	ASSERT(mutex_owned(ST_MUTEX));
9557 
9558 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_wrongtapetype()\n");
9559 
9560 	/*
9561 	 * Hack to handle  600A, 600XTD, 6150 && 660 vs. 300XL tapes...
9562 	 */
9563 	if (un->un_dp && (un->un_dp->options & ST_QIC) && un->un_mspl) {
9564 		switch (un->un_dp->type) {
9565 		case ST_TYPE_WANGTEK:
9566 		case ST_TYPE_ARCHIVE:
9567 			/*
9568 			 * If this really worked, we could go off of
9569 			 * the density codes set in the modesense
9570 			 * page. For this drive, 0x10 == QIC-120,
9571 			 * 0xf == QIC-150, and 0x5 should be for
9572 			 * both QIC-24 and, maybe, QIC-11. However,
9573 			 * the h/w doesn't do what the manual says
9574 			 * that it should, so we'll key off of
9575 			 * getting a WRITE PROTECT error AND wp *not*
9576 			 * set in the mode sense information.
9577 			 */
9578 			/*
9579 			 * XXX but we already know that status is
9580 			 * write protect, so don't check it again.
9581 			 */
9582 
9583 			if (un->un_status == KEY_WRITE_PROTECT &&
9584 			    un->un_mspl->wp == 0) {
9585 				return (1);
9586 			}
9587 			break;
9588 		default:
9589 			break;
9590 		}
9591 	}
9592 	return (0);
9593 }
9594 
9595 static int
9596 st_check_error(struct scsi_tape *un, struct scsi_pkt *pkt)
9597 {
9598 	int action;
9599 
9600 	ST_FUNC(ST_DEVINFO, st_check_error);
9601 
9602 	ASSERT(mutex_owned(ST_MUTEX));
9603 
9604 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_check_error()\n");
9605 
9606 	if (SCBP_C(pkt) == STATUS_RESERVATION_CONFLICT) {
9607 		action = COMMAND_DONE_EACCES;
9608 		un->un_rsvd_status |= ST_RESERVATION_CONFLICT;
9609 	} else if (SCBP(pkt)->sts_busy) {
9610 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG, "unit busy\n");
9611 		if ((int)un->un_retry_ct++ < st_retry_count) {
9612 			action = QUE_BUSY_COMMAND;
9613 		} else if ((un->un_rsvd_status &
9614 		    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
9615 			/*
9616 			 * If this is a command done before reserve is done
9617 			 * don't reset.
9618 			 */
9619 			action = COMMAND_DONE_ERROR;
9620 		} else {
9621 			ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
9622 			    "unit busy too long\n");
9623 			mutex_exit(ST_MUTEX);
9624 			if (scsi_reset(ROUTE, RESET_TARGET) == 0) {
9625 				(void) scsi_reset(ROUTE, RESET_ALL);
9626 			}
9627 			mutex_enter(ST_MUTEX);
9628 			action = COMMAND_DONE_ERROR;
9629 		}
9630 	} else if (SCBP(pkt)->sts_chk) {
9631 		/*
9632 		 * we should only get here if the auto rqsense failed
9633 		 * thru a uscsi cmd without autorequest sense
9634 		 * so we just try again
9635 		 */
9636 		action = QUE_SENSE;
9637 	} else {
9638 		action = COMMAND_DONE;
9639 	}
9640 	return (action);
9641 }
9642 
9643 static void
9644 st_calc_bnum(struct scsi_tape *un, struct buf *bp)
9645 {
9646 	int nblks;
9647 
9648 	ST_FUNC(ST_DEVINFO, st_calc_bnum);
9649 
9650 	ASSERT(mutex_owned(ST_MUTEX));
9651 
9652 	/* If variable block mode */
9653 	if (un->un_bsize == 0) {
9654 		nblks = ((bp->b_bcount - bp->b_resid  == 0) ? 0 : 1);
9655 		un->un_kbytes_xferred += (bp->b_bcount - bp->b_resid) / ONE_K;
9656 	} else {
9657 		nblks = ((bp->b_bcount - bp->b_resid) / un->un_bsize);
9658 		un->un_kbytes_xferred += (nblks * un->un_bsize) / ONE_K;
9659 	}
9660 	un->un_pos.blkno += nblks;
9661 	un->un_pos.lgclblkno += nblks;
9662 }
9663 
9664 static void
9665 st_set_state(struct scsi_tape *un)
9666 {
9667 	struct buf *bp = un->un_runqf;
9668 	struct scsi_pkt *sp = BP_PKT(bp);
9669 	struct uscsi_cmd *ucmd;
9670 
9671 	ST_FUNC(ST_DEVINFO, st_set_state);
9672 
9673 	ASSERT(mutex_owned(ST_MUTEX));
9674 
9675 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9676 	    "st_set_state(): eof=%x	fmneeded=%x  pkt_resid=0x%lx (%ld)\n",
9677 	    un->un_pos.eof, un->un_fmneeded, sp->pkt_resid, sp->pkt_resid);
9678 
9679 	if (bp != un->un_sbufp) {
9680 #ifdef STDEBUG
9681 		if (DEBUGGING && sp->pkt_resid) {
9682 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9683 			    "pkt_resid %ld bcount %ld\n",
9684 			    sp->pkt_resid, bp->b_bcount);
9685 		}
9686 #endif
9687 		bp->b_resid = sp->pkt_resid;
9688 		st_calc_bnum(un, bp);
9689 		if (bp->b_flags & B_READ) {
9690 			un->un_lastop = ST_OP_READ;
9691 			un->un_fmneeded = 0;
9692 		} else {
9693 			un->un_lastop = ST_OP_WRITE;
9694 			if (un->un_dp->options & ST_REEL) {
9695 				un->un_fmneeded = 2;
9696 			} else {
9697 				un->un_fmneeded = 1;
9698 			}
9699 		}
9700 		/*
9701 		 * all is honky dory at this point, so let's
9702 		 * readjust the throttle, to increase speed, if we
9703 		 * have not throttled down.
9704 		 */
9705 		if (un->un_throttle) {
9706 			un->un_throttle = un->un_max_throttle;
9707 		}
9708 	} else {
9709 		optype new_lastop;
9710 		uchar_t cmd = (uchar_t)(intptr_t)bp->b_forw;
9711 
9712 		un->un_lastop = ST_OP_CTL;
9713 
9714 		switch (cmd) {
9715 		case SCMD_WRITE:
9716 			bp->b_resid = sp->pkt_resid;
9717 			new_lastop = ST_OP_WRITE;
9718 			st_calc_bnum(un, bp);
9719 			if (un->un_dp->options & ST_REEL) {
9720 				un->un_fmneeded = 2;
9721 			} else {
9722 				un->un_fmneeded = 1;
9723 			}
9724 			break;
9725 		case SCMD_READ:
9726 			bp->b_resid = sp->pkt_resid;
9727 			new_lastop = ST_OP_READ;
9728 			st_calc_bnum(un, bp);
9729 			un->un_fmneeded = 0;
9730 			break;
9731 		case SCMD_WRITE_FILE_MARK:
9732 		{
9733 			int fmdone;
9734 
9735 			if (un->un_pos.eof != ST_EOM) {
9736 				un->un_pos.eof = ST_NO_EOF;
9737 			}
9738 			fmdone = (bp->b_bcount - bp->b_resid);
9739 			if (fmdone > 0) {
9740 				un->un_lastop = new_lastop = ST_OP_WEOF;
9741 				un->un_pos.lgclblkno += fmdone;
9742 				un->un_pos.fileno += fmdone;
9743 				un->un_pos.blkno = 0;
9744 			} else {
9745 				new_lastop = ST_OP_CTL;
9746 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
9747 				    "Flushed buffer\n");
9748 			}
9749 			if (fmdone > un->un_fmneeded) {
9750 				un->un_fmneeded = 0;
9751 			} else {
9752 				un->un_fmneeded -= fmdone;
9753 			}
9754 			break;
9755 		}
9756 		case SCMD_REWIND:
9757 			un->un_pos.eof = ST_NO_EOF;
9758 			un->un_pos.fileno = 0;
9759 			un->un_pos.blkno = 0;
9760 			un->un_pos.lgclblkno = 0;
9761 			un->un_pos.pmode = legacy;
9762 			new_lastop = ST_OP_CTL;
9763 			break;
9764 
9765 		case SCMD_SPACE:
9766 		{
9767 			int count;
9768 			long resid;
9769 			int done;
9770 
9771 			count = (int)SPACE_CNT(bp->b_bcount);
9772 			/* if was a uscsi space cmd b_bcount == 0 */
9773 			if (count == 0) {
9774 				count =
9775 				    (sp->pkt_cdbp[2] << 16) |
9776 				    (sp->pkt_cdbp[3] << 8)  |
9777 				    (sp->pkt_cdbp[4]);
9778 			}
9779 			resid = (long)SPACE_CNT(bp->b_resid);
9780 			if (count >= 0) {
9781 				done = (count - resid);
9782 			} else {
9783 				done = ((-count) - resid);
9784 			}
9785 			if (done > 0) {
9786 				un->un_lastop = new_lastop = ST_OP_CTL;
9787 			} else {
9788 				new_lastop = ST_OP_CTL;
9789 			}
9790 
9791 			ST_SPAC(ST_DEVINFO, st_label, SCSI_DEBUG,
9792 			    "space cmd: cdb[1] = %s\n"
9793 			    "space data:       = 0x%lx\n"
9794 			    "space count:      = %d\n"
9795 			    "space resid:      = %ld\n"
9796 			    "spaces done:      = %d\n"
9797 			    "fileno before     = %d\n"
9798 			    "blkno before      = %d\n",
9799 			    space_strs[sp->pkt_cdbp[1] & 7],
9800 			    bp->b_bcount,
9801 			    count, resid, done,
9802 			    un->un_pos.fileno, un->un_pos.blkno);
9803 
9804 			switch (sp->pkt_cdbp[1]) {
9805 			case SPACE_TYPE(SP_FLM):
9806 				/* Space file forward */
9807 				if (count >= 0) {
9808 					if (un->un_pos.eof <= ST_EOF) {
9809 						un->un_pos.eof = ST_NO_EOF;
9810 					}
9811 					un->un_pos.fileno += done;
9812 					un->un_pos.blkno = 0;
9813 					break;
9814 				}
9815 				/* Space file backward */
9816 				if (done > un->un_pos.fileno) {
9817 					un->un_pos.fileno = 0;
9818 					un->un_pos.blkno = 0;
9819 				} else {
9820 					un->un_pos.fileno -= done;
9821 					un->un_pos.blkno = INF;
9822 				}
9823 				break;
9824 			case SPACE_TYPE(SP_BLK):
9825 				/* Space block forward */
9826 				if (count >= 0) {
9827 					un->un_pos.blkno += done;
9828 					break;
9829 				}
9830 				/* Space block backward */
9831 				if (un->un_pos.eof >= ST_EOF_PENDING) {
9832 				/*
9833 				 * we stepped back into
9834 				 * a previous file; we are not
9835 				 * making an effort to pretend that
9836 				 * we are still in the current file
9837 				 * ie. logical == physical position
9838 				 * and leave it to st_ioctl to correct
9839 				 */
9840 					if (done > un->un_pos.blkno) {
9841 						un->un_pos.blkno = 0;
9842 					} else {
9843 						un->un_pos.fileno--;
9844 						un->un_pos.blkno = INF;
9845 					}
9846 				} else {
9847 					un->un_pos.blkno -= done;
9848 				}
9849 				break;
9850 			case SPACE_TYPE(SP_SQFLM):
9851 				un->un_pos.pmode = logical;
9852 				un->un_pos.blkno = 0;
9853 				un->un_lastop = new_lastop = ST_OP_CTL;
9854 				break;
9855 			case SPACE_TYPE(SP_EOD):
9856 				un->un_pos.pmode = logical;
9857 				un->un_pos.eof = ST_EOM;
9858 				un->un_status = KEY_BLANK_CHECK;
9859 				break;
9860 			default:
9861 				un->un_pos.pmode = invalid;
9862 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
9863 				    "Unsupported space cmd: %s\n",
9864 				    space_strs[sp->pkt_cdbp[1] & 7]);
9865 
9866 				un->un_lastop = new_lastop = ST_OP_CTL;
9867 			}
9868 
9869 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9870 			    "after_space rs %ld fil %d blk %d\n",
9871 			    resid, un->un_pos.fileno, un->un_pos.blkno);
9872 
9873 			break;
9874 		}
9875 		case SCMD_LOAD:
9876 			if ((bp->b_bcount & (LD_LOAD | LD_EOT)) == LD_LOAD) {
9877 				un->un_pos.fileno = 0;
9878 				un->un_pos.pmode = legacy;
9879 			} else {
9880 				un->un_state = ST_STATE_OFFLINE;
9881 				un->un_pos.pmode = invalid;
9882 			}
9883 			un->un_density_known = 0;
9884 			un->un_pos.eof = ST_NO_EOF;
9885 			un->un_pos.blkno = 0;
9886 			un->un_lastop = new_lastop = ST_OP_CTL;
9887 			break;
9888 		case SCMD_ERASE:
9889 			un->un_pos.eof = ST_NO_EOF;
9890 			un->un_pos.blkno = 0;
9891 			un->un_pos.fileno = 0;
9892 			un->un_pos.lgclblkno = 0;
9893 			un->un_pos.pmode = legacy;
9894 			new_lastop = ST_OP_CTL;
9895 			break;
9896 		case SCMD_RESERVE:
9897 			un->un_rsvd_status |= ST_RESERVE;
9898 			un->un_rsvd_status &=
9899 			    ~(ST_RELEASE | ST_LOST_RESERVE |
9900 			    ST_RESERVATION_CONFLICT);
9901 			new_lastop = un->un_lastop;
9902 			break;
9903 		case SCMD_RELEASE:
9904 			un->un_rsvd_status |= ST_RELEASE;
9905 			un->un_rsvd_status &=
9906 			    ~(ST_RESERVE | ST_LOST_RESERVE |
9907 			    ST_RESERVATION_CONFLICT);
9908 			new_lastop = ST_OP_CTL;
9909 			break;
9910 		case SCMD_PERSISTENT_RESERVE_IN:
9911 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9912 			    "PGR_IN command\n");
9913 			break;
9914 		case SCMD_PERSISTENT_RESERVE_OUT:
9915 			switch (sp->pkt_cdbp[1] & ST_SA_MASK) {
9916 			case ST_SA_SCSI3_RESERVE:
9917 			case ST_SA_SCSI3_PREEMPT:
9918 			case ST_SA_SCSI3_PREEMPTANDABORT:
9919 				un->un_rsvd_status |=
9920 				    ST_APPLICATION_RESERVATIONS;
9921 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9922 				    "PGR Reserve and set: entering"
9923 				    " ST_APPLICATION_RESERVATIONS mode");
9924 				break;
9925 			case ST_SA_SCSI3_RELEASE:
9926 			case ST_SA_SCSI3_CLEAR:
9927 				un->un_rsvd_status &=
9928 				    ~ST_APPLICATION_RESERVATIONS;
9929 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9930 				    "PGR Release and reset: exiting"
9931 				    " ST_APPLICATION_RESERVATIONS mode");
9932 				break;
9933 			}
9934 			break;
9935 		case SCMD_TEST_UNIT_READY:
9936 		case SCMD_READ_BLKLIM:
9937 		case SCMD_REQUEST_SENSE:
9938 		case SCMD_INQUIRY:
9939 		case SCMD_RECOVER_BUF:
9940 		case SCMD_MODE_SELECT:
9941 		case SCMD_MODE_SENSE:
9942 		case SCMD_DOORLOCK:
9943 		case SCMD_READ_BUFFER:
9944 		case SCMD_REPORT_DENSITIES:
9945 		case SCMD_LOG_SELECT_G1:
9946 		case SCMD_LOG_SENSE_G1:
9947 		case SCMD_REPORT_LUNS:
9948 		case SCMD_READ_ATTRIBUTE:
9949 		case SCMD_READ_MEDIA_SERIAL:
9950 			new_lastop = ST_OP_CTL;
9951 			break;
9952 		case SCMD_READ_POSITION:
9953 			new_lastop = ST_OP_CTL;
9954 			if (USCSI_CMD(bp)) {
9955 				(void) st_get_read_pos(un, bp);
9956 			}
9957 			break;
9958 		case SCMD_LOCATE:
9959 		case SCMD_LOCATE_G4:
9960 			/* Locate makes position mode no longer legacy */
9961 			un->un_lastop = new_lastop = ST_OP_CTL;
9962 			break;
9963 		default:
9964 			/*
9965 			 * Unknown command, If was USCSI and USCSI_SILENT
9966 			 * flag was not set, set position to unknown.
9967 			 */
9968 			if ((((ucmd = BP_UCMD(bp)) != NULL) &&
9969 			    (ucmd->uscsi_flags & USCSI_SILENT) == 0)) {
9970 				ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
9971 				    "unknown cmd 0x%X caused loss of state\n",
9972 				    cmd);
9973 			} else {
9974 				break;
9975 			}
9976 			/* FALLTHROUGH */
9977 		case SCMD_WRITE_BUFFER: /* Writes new firmware to device */
9978 			un->un_pos.pmode = invalid;
9979 			un->un_lastop = new_lastop = ST_OP_CTL;
9980 			break;
9981 		}
9982 
9983 		/* new_lastop should have been changed */
9984 		ASSERT(new_lastop != ST_OP_NIL);
9985 
9986 		/* If un_lastop should copy new_lastop  */
9987 		if (((un->un_lastop == ST_OP_WRITE) ||
9988 		    (un->un_lastop == ST_OP_WEOF)) &&
9989 		    new_lastop != ST_OP_CTL) {
9990 			un->un_lastop = new_lastop;
9991 		}
9992 	}
9993 
9994 	/*
9995 	 * In the st driver we have a logical and physical file position.
9996 	 * Under BSD behavior, when you get a zero read, the logical position
9997 	 * is before the filemark but after the last record of the file.
9998 	 * The physical position is after the filemark. MTIOCGET should always
9999 	 * return the logical file position.
10000 	 *
10001 	 * The next read gives a silent skip to the next file.
10002 	 * Under SVR4, the logical file position remains before the filemark
10003 	 * until the file is closed or a space operation is performed.
10004 	 * Hence set err_resid and err_file before changing fileno if case
10005 	 * BSD Behaviour.
10006 	 */
10007 	un->un_err_resid = bp->b_resid;
10008 	COPY_POS(&un->un_err_pos, &un->un_pos);
10009 	un->un_retry_ct = 0;
10010 
10011 
10012 	/*
10013 	 * If we've seen a filemark via the last read operation
10014 	 * advance the file counter, but mark things such that
10015 	 * the next read operation gets a zero count. We have
10016 	 * to put this here to handle the case of sitting right
10017 	 * at the end of a tape file having seen the file mark,
10018 	 * but the tape is closed and then re-opened without
10019 	 * any further i/o. That is, the position information
10020 	 * must be updated before a close.
10021 	 */
10022 
10023 	if (un->un_lastop == ST_OP_READ && un->un_pos.eof == ST_EOF_PENDING) {
10024 		/*
10025 		 * If we're a 1/2" tape, and we get a filemark
10026 		 * right on block 0, *AND* we were not in the
10027 		 * first file on the tape, and we've hit logical EOM.
10028 		 * We'll mark the state so that later we do the
10029 		 * right thing (in st_close(), st_strategy() or
10030 		 * st_ioctl()).
10031 		 *
10032 		 */
10033 		if ((un->un_dp->options & ST_REEL) &&
10034 		    !(un->un_dp->options & ST_READ_IGNORE_EOFS) &&
10035 		    un->un_pos.blkno == 0 && un->un_pos.fileno > 0) {
10036 			un->un_pos.eof = ST_EOT_PENDING;
10037 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10038 			    "eot pending\n");
10039 			un->un_pos.fileno++;
10040 			un->un_pos.blkno = 0;
10041 		} else if (BSD_BEHAVIOR) {
10042 			/*
10043 			 * If the read of the filemark was a side effect
10044 			 * of reading some blocks (i.e., data was actually
10045 			 * read), then the EOF mark is pending and the
10046 			 * bump into the next file awaits the next read
10047 			 * operation (which will return a zero count), or
10048 			 * a close or a space operation, else the bump
10049 			 * into the next file occurs now.
10050 			 */
10051 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10052 			    "resid=%lx, bcount=%lx\n",
10053 			    bp->b_resid, bp->b_bcount);
10054 
10055 			if (bp->b_resid != bp->b_bcount) {
10056 				un->un_pos.eof = ST_EOF;
10057 			} else {
10058 				un->un_silent_skip = 1;
10059 				un->un_pos.eof = ST_NO_EOF;
10060 				un->un_pos.fileno++;
10061 				un->un_pos.lgclblkno++;
10062 				un->un_save_blkno = un->un_pos.blkno;
10063 				un->un_pos.blkno = 0;
10064 			}
10065 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10066 			    "eof of file %d, eof=%d\n",
10067 			    un->un_pos.fileno, un->un_pos.eof);
10068 		} else if (SVR4_BEHAVIOR) {
10069 			/*
10070 			 * If the read of the filemark was a side effect
10071 			 * of reading some blocks (i.e., data was actually
10072 			 * read), then the next read should return 0
10073 			 */
10074 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10075 			    "resid=%lx, bcount=%lx\n",
10076 			    bp->b_resid, bp->b_bcount);
10077 			if (bp->b_resid == bp->b_bcount) {
10078 				un->un_pos.eof = ST_EOF;
10079 			}
10080 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10081 			    "eof of file=%d, eof=%d\n",
10082 			    un->un_pos.fileno, un->un_pos.eof);
10083 		}
10084 	}
10085 }
10086 
10087 /*
10088  * set the correct un_errno, to take corner cases into consideration
10089  */
10090 static void
10091 st_set_pe_errno(struct scsi_tape *un)
10092 {
10093 	ST_FUNC(ST_DEVINFO, st_set_pe_errno);
10094 
10095 	ASSERT(mutex_owned(ST_MUTEX));
10096 
10097 	/* if errno is already set, don't reset it */
10098 	if (un->un_errno)
10099 		return;
10100 
10101 	/* here un_errno == 0 */
10102 	/*
10103 	 * if the last transfer before flushing all the
10104 	 * waiting I/O's, was 0 (resid = count), then we
10105 	 * want to give the user an error on all the rest,
10106 	 * so here.  If there was a transfer, we set the
10107 	 * resid and counts to 0, and let it drop through,
10108 	 * giving a zero return.  the next I/O will then
10109 	 * give an error.
10110 	 */
10111 	if (un->un_last_resid == un->un_last_count) {
10112 		switch (un->un_pos.eof) {
10113 		case ST_EOM:
10114 			un->un_errno = ENOMEM;
10115 			break;
10116 		case ST_EOT:
10117 		case ST_EOF:
10118 			un->un_errno = EIO;
10119 			break;
10120 		}
10121 	} else {
10122 		/*
10123 		 * we know they did not have a zero, so make
10124 		 * sure they get one
10125 		 */
10126 		un->un_last_resid = un->un_last_count = 0;
10127 	}
10128 }
10129 
10130 
10131 /*
10132  * send in a marker pkt to terminate flushing of commands by BBA (via
10133  * flush-on-errors) property.  The HBA will always return TRAN_ACCEPT
10134  */
10135 static void
10136 st_hba_unflush(struct scsi_tape *un)
10137 {
10138 	ST_FUNC(ST_DEVINFO, st_hba_unflush);
10139 
10140 	ASSERT(mutex_owned(ST_MUTEX));
10141 
10142 	if (!un->un_flush_on_errors)
10143 		return;
10144 
10145 #ifdef FLUSH_ON_ERRORS
10146 
10147 	if (!un->un_mkr_pkt) {
10148 		un->un_mkr_pkt = scsi_init_pkt(ROUTE, NULL, (struct buf *)NULL,
10149 		    NULL, 0, 0, 0, SLEEP_FUNC, NULL);
10150 
10151 		/* we slept, so it must be there */
10152 		pkt->pkt_flags |= FLAG_FLUSH_MARKER;
10153 	}
10154 
10155 	mutex_exit(ST_MUTEX);
10156 	scsi_transport(un->un_mkr_pkt);
10157 	mutex_enter(ST_MUTEX);
10158 #endif
10159 }
10160 
10161 static char *
10162 st_print_scsi_cmd(char cmd)
10163 {
10164 	char tmp[64];
10165 	char *cpnt;
10166 
10167 	cpnt = scsi_cmd_name(cmd, scsi_cmds, tmp);
10168 	/* tmp goes out of scope on return and caller sees garbage */
10169 	if (cpnt == tmp) {
10170 		cpnt = "Unknown Command";
10171 	}
10172 	return (cpnt);
10173 }
10174 
10175 static void
10176 st_print_cdb(dev_info_t *dip, char *label, uint_t level,
10177     char *title, char *cdb)
10178 {
10179 	int len = scsi_cdb_size[CDB_GROUPID(cdb[0])];
10180 	char buf[256];
10181 	int instance = ddi_get_instance(dip);
10182 	struct scsi_tape *un;
10183 
10184 	un = ddi_get_soft_state(st_state, instance);
10185 
10186 	ST_FUNC(dip, st_print_cdb);
10187 
10188 #ifdef DEBUG
10189 	if ((st_debug & 0x180) == 0x100) {
10190 		scsi_log(dip, label, level, "node %s cmd %s\n",
10191 		    st_dev_name(un->un_dev), st_print_scsi_cmd(*cdb));
10192 		return;
10193 	}
10194 #endif
10195 	(void) sprintf(buf, "%s for cmd(%s)", title, st_print_scsi_cmd(*cdb));
10196 	st_clean_print(dip, label, level, buf, cdb, len);
10197 }
10198 
10199 static void
10200 st_clean_print(dev_info_t *dev, char *label, uint_t level,
10201     char *title, char *data, int len)
10202 {
10203 	int	i;
10204 	int 	c;
10205 	char	*format;
10206 	char	buf[256];
10207 	uchar_t	byte;
10208 
10209 	ST_FUNC(dev, st_clean_print);
10210 
10211 	(void) sprintf(buf, "%s:\n", title);
10212 	scsi_log(dev, label, level, "%s", buf);
10213 	level = CE_CONT;
10214 	for (i = 0; i < len; ) {
10215 		buf[0] = 0;
10216 		for (c = 0; c < 8 && i < len; c++, i++) {
10217 			byte = (uchar_t)data[i];
10218 			if (byte < 0x10)
10219 				format = "0x0%x ";
10220 			else
10221 				format = "0x%x ";
10222 			(void) sprintf(&buf[(int)strlen(buf)], format, byte);
10223 		}
10224 		(void) sprintf(&buf[(int)strlen(buf)], "\n");
10225 
10226 		scsi_log(dev, label, level, "%s\n", buf);
10227 	}
10228 }
10229 
10230 /*
10231  * Conditionally enabled debugging
10232  */
10233 #ifdef	STDEBUG
10234 static void
10235 st_debug_cmds(struct scsi_tape *un, int com, int count, int wait)
10236 {
10237 	char tmpbuf[64];
10238 
10239 	ST_FUNC(ST_DEVINFO, st_debug_cmds);
10240 
10241 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10242 	    "cmd=%s count=0x%x (%d)	 %ssync\n",
10243 	    scsi_cmd_name(com, scsi_cmds, tmpbuf),
10244 	    count, count,
10245 	    wait == ASYNC_CMD ? "a" : "");
10246 }
10247 
10248 /*
10249  * Returns pointer to name of minor node name of device 'dev'.
10250  */
10251 static char *
10252 st_dev_name(dev_t dev)
10253 {
10254 	struct scsi_tape *un;
10255 	const char density[] = { 'l', 'm', 'h', 'c' };
10256 	static char name[4];
10257 	minor_t minor;
10258 	int instance;
10259 	int nprt = 0;
10260 
10261 	minor = getminor(dev);
10262 	instance = ((minor & 0xff80) >> 5) | (minor & 3);
10263 	un = ddi_get_soft_state(st_state, instance);
10264 	if (un) {
10265 		ST_FUNC(ST_DEVINFO, st_dev_name);
10266 	}
10267 
10268 	name[nprt] = density[(minor & MT_DENSITY_MASK) >> 3];
10269 
10270 	if (minor & MT_BSD) {
10271 		name[++nprt] = 'b';
10272 	}
10273 
10274 	if (minor & MT_NOREWIND) {
10275 		name[++nprt] = 'n';
10276 	}
10277 
10278 	/* NULL terminator */
10279 	name[++nprt] = 0;
10280 
10281 	return (name);
10282 }
10283 #endif	/* STDEBUG */
10284 
10285 /*
10286  * Soft error reporting, so far unique to each drive
10287  *
10288  * Currently supported: exabyte and DAT soft error reporting
10289  */
10290 static int
10291 st_report_exabyte_soft_errors(dev_t dev, int flag)
10292 {
10293 	uchar_t *sensep;
10294 	int amt;
10295 	int rval = 0;
10296 	char cdb[CDB_GROUP0], *c = cdb;
10297 	struct uscsi_cmd *com;
10298 
10299 	GET_SOFT_STATE(dev);
10300 
10301 	ST_FUNC(ST_DEVINFO, st_report_exabyte_soft_errors);
10302 
10303 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10304 	    "st_report_exabyte_soft_errors(dev = 0x%lx, flag = %d)\n",
10305 	    dev, flag);
10306 
10307 	ASSERT(mutex_owned(ST_MUTEX));
10308 
10309 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
10310 	sensep = kmem_zalloc(TAPE_SENSE_LENGTH, KM_SLEEP);
10311 
10312 	*c++ = SCMD_REQUEST_SENSE;
10313 	*c++ = 0;
10314 	*c++ = 0;
10315 	*c++ = 0;
10316 	*c++ = TAPE_SENSE_LENGTH;
10317 	/*
10318 	 * set CLRCNT (byte 5, bit 7 which clears the error counts)
10319 	 */
10320 	*c   = (char)0x80;
10321 
10322 	com->uscsi_cdb = cdb;
10323 	com->uscsi_cdblen = CDB_GROUP0;
10324 	com->uscsi_bufaddr = (caddr_t)sensep;
10325 	com->uscsi_buflen = TAPE_SENSE_LENGTH;
10326 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
10327 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
10328 
10329 	rval = st_ioctl_cmd(dev, com, FKIOCTL);
10330 	if (rval || com->uscsi_status) {
10331 		goto done;
10332 	}
10333 
10334 	/*
10335 	 * was there enough data?
10336 	 */
10337 	amt = (int)TAPE_SENSE_LENGTH - com->uscsi_resid;
10338 
10339 	if ((amt >= 19) && un->un_kbytes_xferred) {
10340 		uint_t count, error_rate;
10341 		uint_t rate;
10342 
10343 		if (sensep[21] & CLN) {
10344 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
10345 			    "Periodic head cleaning required");
10346 		}
10347 		if (un->un_kbytes_xferred < (EXABYTE_MIN_TRANSFER/ONE_K)) {
10348 			goto done;
10349 		}
10350 		/*
10351 		 * check if soft error reporting needs to be done.
10352 		 */
10353 		count = sensep[16] << 16 | sensep[17] << 8 | sensep[18];
10354 		count &= 0xffffff;
10355 		error_rate = (count * 100)/un->un_kbytes_xferred;
10356 
10357 #ifdef	STDEBUG
10358 		if (st_soft_error_report_debug) {
10359 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
10360 			    "Exabyte Soft Error Report:\n");
10361 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
10362 			    "read/write error counter: %d\n", count);
10363 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
10364 			    "number of bytes transferred: %dK\n",
10365 			    un->un_kbytes_xferred);
10366 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
10367 			    "error_rate: %d%%\n", error_rate);
10368 
10369 			if (amt >= 22) {
10370 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
10371 				    "unit sense: 0x%b 0x%b 0x%b\n",
10372 				    sensep[19], SENSE_19_BITS,
10373 				    sensep[20], SENSE_20_BITS,
10374 				    sensep[21], SENSE_21_BITS);
10375 			}
10376 			if (amt >= 27) {
10377 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
10378 				    "tracking retry counter: %d\n",
10379 				    sensep[26]);
10380 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
10381 				    "read/write retry counter: %d\n",
10382 				    sensep[27]);
10383 			}
10384 		}
10385 #endif
10386 
10387 		if (flag & FWRITE) {
10388 			rate = EXABYTE_WRITE_ERROR_THRESHOLD;
10389 		} else {
10390 			rate = EXABYTE_READ_ERROR_THRESHOLD;
10391 		}
10392 		if (error_rate >= rate) {
10393 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
10394 			    "Soft error rate (%d%%) during %s was too high",
10395 			    error_rate,
10396 			    ((flag & FWRITE) ? wrg_str : rdg_str));
10397 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
10398 			    "Please, replace tape cartridge\n");
10399 		}
10400 	}
10401 
10402 done:
10403 	kmem_free(com, sizeof (*com));
10404 	kmem_free(sensep, TAPE_SENSE_LENGTH);
10405 
10406 	if (rval != 0) {
10407 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
10408 		    "exabyte soft error reporting failed\n");
10409 	}
10410 	return (rval);
10411 }
10412 
10413 /*
10414  * this is very specific to Archive 4mm dat
10415  */
10416 #define	ONE_GIG	(ONE_K * ONE_K * ONE_K)
10417 
10418 static int
10419 st_report_dat_soft_errors(dev_t dev, int flag)
10420 {
10421 	uchar_t *sensep;
10422 	int amt, i;
10423 	int rval = 0;
10424 	char cdb[CDB_GROUP1], *c = cdb;
10425 	struct uscsi_cmd *com;
10426 
10427 	GET_SOFT_STATE(dev);
10428 
10429 	ST_FUNC(ST_DEVINFO, st_report_dat_soft_errors);
10430 
10431 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10432 	    "st_report_dat_soft_errors(dev = 0x%lx, flag = %d)\n", dev, flag);
10433 
10434 	ASSERT(mutex_owned(ST_MUTEX));
10435 
10436 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
10437 	sensep = kmem_zalloc(LOG_SENSE_LENGTH, KM_SLEEP);
10438 
10439 	*c++ = SCMD_LOG_SENSE_G1;
10440 	*c++ = 0;
10441 	*c++ = (flag & FWRITE) ? 0x42 : 0x43;
10442 	*c++ = 0;
10443 	*c++ = 0;
10444 	*c++ = 0;
10445 	*c++ = 2;
10446 	*c++ = 0;
10447 	*c++ = (char)LOG_SENSE_LENGTH;
10448 	*c   = 0;
10449 	com->uscsi_cdb    = cdb;
10450 	com->uscsi_cdblen  = CDB_GROUP1;
10451 	com->uscsi_bufaddr = (caddr_t)sensep;
10452 	com->uscsi_buflen  = LOG_SENSE_LENGTH;
10453 	com->uscsi_flags   =
10454 	    USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
10455 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
10456 	rval = st_ioctl_cmd(dev, com, FKIOCTL);
10457 	if (rval) {
10458 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
10459 		    "DAT soft error reporting failed\n");
10460 	}
10461 	if (rval || com->uscsi_status) {
10462 		goto done;
10463 	}
10464 
10465 	/*
10466 	 * was there enough data?
10467 	 */
10468 	amt = (int)LOG_SENSE_LENGTH - com->uscsi_resid;
10469 
10470 	if ((amt >= MIN_LOG_SENSE_LENGTH) && un->un_kbytes_xferred) {
10471 		int total, retries, param_code;
10472 
10473 		total = -1;
10474 		retries = -1;
10475 		amt = sensep[3] + 4;
10476 
10477 
10478 #ifdef STDEBUG
10479 		if (st_soft_error_report_debug) {
10480 			(void) printf("logsense:");
10481 			for (i = 0; i < MIN_LOG_SENSE_LENGTH; i++) {
10482 				if (i % 16 == 0) {
10483 					(void) printf("\t\n");
10484 				}
10485 				(void) printf(" %x", sensep[i]);
10486 			}
10487 			(void) printf("\n");
10488 		}
10489 #endif
10490 
10491 		/*
10492 		 * parse the param_codes
10493 		 */
10494 		if (sensep[0] == 2 || sensep[0] == 3) {
10495 			for (i = 4; i < amt; i++) {
10496 				param_code = (sensep[i++] << 8);
10497 				param_code += sensep[i++];
10498 				i++; /* skip control byte */
10499 				if (param_code == 5) {
10500 					if (sensep[i++] == 4) {
10501 						total = (sensep[i++] << 24);
10502 						total += (sensep[i++] << 16);
10503 						total += (sensep[i++] << 8);
10504 						total += sensep[i];
10505 					}
10506 				} else if (param_code == 0x8007) {
10507 					if (sensep[i++] == 2) {
10508 						retries = sensep[i++] << 8;
10509 						retries += sensep[i];
10510 					}
10511 				} else {
10512 					i += sensep[i];
10513 				}
10514 			}
10515 		}
10516 
10517 		/*
10518 		 * if the log sense returned valid numbers then determine
10519 		 * the read and write error thresholds based on the amount of
10520 		 * data transferred
10521 		 */
10522 
10523 		if (total > 0 && retries > 0) {
10524 			short normal_retries = 0;
10525 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10526 			    "total xferred (%s) =%x, retries=%x\n",
10527 			    ((flag & FWRITE) ? wrg_str : rdg_str),
10528 			    total, retries);
10529 
10530 			if (flag & FWRITE) {
10531 				if (total <=
10532 				    WRITE_SOFT_ERROR_WARNING_THRESHOLD) {
10533 					normal_retries =
10534 					    DAT_SMALL_WRITE_ERROR_THRESHOLD;
10535 				} else {
10536 					normal_retries =
10537 					    DAT_LARGE_WRITE_ERROR_THRESHOLD;
10538 				}
10539 			} else {
10540 				if (total <=
10541 				    READ_SOFT_ERROR_WARNING_THRESHOLD) {
10542 					normal_retries =
10543 					    DAT_SMALL_READ_ERROR_THRESHOLD;
10544 				} else {
10545 					normal_retries =
10546 					    DAT_LARGE_READ_ERROR_THRESHOLD;
10547 				}
10548 			}
10549 
10550 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10551 			"normal retries=%d\n", normal_retries);
10552 
10553 			if (retries >= normal_retries) {
10554 				scsi_log(ST_DEVINFO, st_label, CE_WARN,
10555 				    "Soft error rate (retries = %d) during "
10556 				    "%s was too high",  retries,
10557 				    ((flag & FWRITE) ? wrg_str : rdg_str));
10558 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
10559 				    "Periodic head cleaning required "
10560 				    "and/or replace tape cartridge\n");
10561 			}
10562 
10563 		} else if (total == -1 || retries == -1) {
10564 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
10565 			    "log sense parameter code does not make sense\n");
10566 		}
10567 	}
10568 
10569 	/*
10570 	 * reset all values
10571 	 */
10572 	c = cdb;
10573 	*c++ = SCMD_LOG_SELECT_G1;
10574 	*c++ = 2;	/* this resets all values */
10575 	*c++ = (char)0xc0;
10576 	*c++ = 0;
10577 	*c++ = 0;
10578 	*c++ = 0;
10579 	*c++ = 0;
10580 	*c++ = 0;
10581 	*c++ = 0;
10582 	*c   = 0;
10583 	com->uscsi_bufaddr = NULL;
10584 	com->uscsi_buflen  = 0;
10585 	com->uscsi_flags   = USCSI_DIAGNOSE | USCSI_SILENT;
10586 	rval = st_ioctl_cmd(dev, com, FKIOCTL);
10587 	if (rval) {
10588 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
10589 		    "DAT soft error reset failed\n");
10590 	}
10591 done:
10592 	kmem_free(com, sizeof (*com));
10593 	kmem_free(sensep, LOG_SENSE_LENGTH);
10594 	return (rval);
10595 }
10596 
10597 static int
10598 st_report_soft_errors(dev_t dev, int flag)
10599 {
10600 	GET_SOFT_STATE(dev);
10601 
10602 	ST_FUNC(ST_DEVINFO, st_report_soft_errors);
10603 
10604 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10605 	    "st_report_soft_errors(dev = 0x%lx, flag = %d)\n", dev, flag);
10606 
10607 	ASSERT(mutex_owned(ST_MUTEX));
10608 
10609 	switch (un->un_dp->type) {
10610 	case ST_TYPE_EXB8500:
10611 	case ST_TYPE_EXABYTE:
10612 		return (st_report_exabyte_soft_errors(dev, flag));
10613 		/*NOTREACHED*/
10614 	case ST_TYPE_PYTHON:
10615 		return (st_report_dat_soft_errors(dev, flag));
10616 		/*NOTREACHED*/
10617 	default:
10618 		un->un_dp->options &= ~ST_SOFT_ERROR_REPORTING;
10619 		return (-1);
10620 	}
10621 }
10622 
10623 /*
10624  * persistent error routines
10625  */
10626 
10627 /*
10628  * enable persistent errors, and set the throttle appropriately, checking
10629  * for flush-on-errors capability
10630  */
10631 static void
10632 st_turn_pe_on(struct scsi_tape *un)
10633 {
10634 	ST_FUNC(ST_DEVINFO, st_turn_pe_on);
10635 
10636 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_on\n");
10637 	ASSERT(mutex_owned(ST_MUTEX));
10638 
10639 	un->un_persistence = 1;
10640 
10641 	/*
10642 	 * only use flush-on-errors if auto-request-sense and untagged-qing are
10643 	 * enabled.  This will simplify the error handling for request senses
10644 	 */
10645 
10646 	if (un->un_arq_enabled && un->un_untagged_qing) {
10647 		uchar_t f_o_e;
10648 
10649 		mutex_exit(ST_MUTEX);
10650 		f_o_e = (scsi_ifsetcap(ROUTE, "flush-on-errors", 1, 1) == 1) ?
10651 		    1 : 0;
10652 		mutex_enter(ST_MUTEX);
10653 
10654 		un->un_flush_on_errors = f_o_e;
10655 	} else {
10656 		un->un_flush_on_errors = 0;
10657 	}
10658 
10659 	if (un->un_flush_on_errors)
10660 		un->un_max_throttle = (uchar_t)st_max_throttle;
10661 	else
10662 		un->un_max_throttle = 1;
10663 
10664 	if (un->un_dp->options & ST_RETRY_ON_RECOVERED_DEFERRED_ERROR)
10665 		un->un_max_throttle = 1;
10666 
10667 	/* this will send a marker pkt */
10668 	CLEAR_PE(un);
10669 }
10670 
10671 /*
10672  * This turns persistent errors permanently off
10673  */
10674 static void
10675 st_turn_pe_off(struct scsi_tape *un)
10676 {
10677 	ST_FUNC(ST_DEVINFO, st_turn_pe_off);
10678 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_off\n");
10679 	ASSERT(mutex_owned(ST_MUTEX));
10680 
10681 	/* turn it off for good */
10682 	un->un_persistence = 0;
10683 
10684 	/* this will send a marker pkt */
10685 	CLEAR_PE(un);
10686 
10687 	/* turn off flush on error capability, if enabled */
10688 	if (un->un_flush_on_errors) {
10689 		mutex_exit(ST_MUTEX);
10690 		(void) scsi_ifsetcap(ROUTE, "flush-on-errors", 0, 1);
10691 		mutex_enter(ST_MUTEX);
10692 	}
10693 
10694 
10695 	un->un_flush_on_errors = 0;
10696 }
10697 
10698 /*
10699  * This clear persistent errors, allowing more commands through, and also
10700  * sending a marker packet.
10701  */
10702 static void
10703 st_clear_pe(struct scsi_tape *un)
10704 {
10705 	ST_FUNC(ST_DEVINFO, st_clear_pe);
10706 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_clear\n");
10707 	ASSERT(mutex_owned(ST_MUTEX));
10708 
10709 	un->un_persist_errors = 0;
10710 	un->un_throttle = un->un_last_throttle = 1;
10711 	un->un_errno = 0;
10712 	st_hba_unflush(un);
10713 }
10714 
10715 /*
10716  * This will flag persistent errors, shutting everything down, if the
10717  * application had enabled persistent errors via MTIOCPERSISTENT
10718  */
10719 static void
10720 st_set_pe_flag(struct scsi_tape *un)
10721 {
10722 	ST_FUNC(ST_DEVINFO, st_set_pe_flag);
10723 	ASSERT(mutex_owned(ST_MUTEX));
10724 
10725 	if (un->un_persistence) {
10726 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_flag\n");
10727 		un->un_persist_errors = 1;
10728 		un->un_throttle = un->un_last_throttle = 0;
10729 	}
10730 }
10731 
10732 /*
10733  * List of commands that are allowed to be done while another host holds
10734  * the reservation.
10735  */
10736 struct {
10737 	uchar_t cmd;
10738 	uchar_t byte;	/* byte to look for data */
10739 	uint32_t mask;	/* bits that matter in the above data */
10740 } rcmds[] = {
10741 	{ SCMD_TEST_UNIT_READY, 0, 0 }, /* may fail on older drives */
10742 	{ SCMD_REQUEST_SENSE, 0, 0 },
10743 	{ SCMD_READ_BLKLIM, 0, 0 },
10744 	{ SCMD_INQUIRY, 0, 0 },
10745 	{ SCMD_RESERVE, 0, 0 },
10746 	{ SCMD_RELEASE, 0, 0 },
10747 	{ SCMD_DOORLOCK, 4, 3 },	/* allow (unlock) media access only */
10748 	{ SCMD_REPORT_DENSITIES, 0, 0 },
10749 	{ SCMD_LOG_SENSE_G1, 0, 0 },
10750 	{ SCMD_PERSISTENT_RESERVE_IN, 0, 0 },
10751 	{ SCMD_PERSISTENT_RESERVE_OUT, 0, 0 },
10752 	{ SCMD_REPORT_LUNS, 0, 0 }
10753 };
10754 
10755 static int
10756 st_do_reserve(struct scsi_tape *un)
10757 {
10758 	int rval;
10759 
10760 	ST_FUNC(ST_DEVINFO, st_do_reserve);
10761 
10762 	/*
10763 	 * Issue a Throw-Away reserve command to clear the
10764 	 * check condition.
10765 	 * If the current behaviour of reserve/release is to
10766 	 * hold reservation across opens , and if a Bus reset
10767 	 * has been issued between opens then this command
10768 	 * would set the ST_LOST_RESERVE flags in rsvd_status.
10769 	 * In this case return an EACCES so that user knows that
10770 	 * reservation has been lost in between opens.
10771 	 * If this error is not returned and we continue with
10772 	 * successful open , then user may think position of the
10773 	 * tape is still the same but inreality we would rewind the
10774 	 * tape and continue from BOT.
10775 	 */
10776 	rval = st_reserve_release(un, ST_RESERVE);
10777 	if (rval) {
10778 		if ((un->un_rsvd_status & ST_LOST_RESERVE_BETWEEN_OPENS) ==
10779 		    ST_LOST_RESERVE_BETWEEN_OPENS) {
10780 			un->un_rsvd_status &= ~(ST_LOST_RESERVE | ST_RESERVE);
10781 			un->un_errno = EACCES;
10782 			return (EACCES);
10783 		}
10784 		rval = st_reserve_release(un, ST_RESERVE);
10785 	}
10786 	if (rval == 0) {
10787 		un->un_rsvd_status |= ST_INIT_RESERVE;
10788 	}
10789 
10790 	return (rval);
10791 }
10792 
10793 static int
10794 st_check_cdb_for_need_to_reserve(struct scsi_tape *un, caddr_t cdb)
10795 {
10796 	int i;
10797 	int rval = 0;
10798 
10799 	ST_FUNC(ST_DEVINFO, st_check_cdb_for_need_to_reserve);
10800 
10801 	/*
10802 	 * If already reserved no need to do it again.
10803 	 * Also if Reserve and Release are disabled Just return.
10804 	 */
10805 	if ((un->un_rsvd_status & (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) ||
10806 	    (un->un_dp->options & ST_NO_RESERVE_RELEASE)) {
10807 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
10808 		    "st_check_cdb_for_need_to_reserve() reserve unneeded %s",
10809 		    st_print_scsi_cmd((uchar_t)cdb[0]));
10810 		return (0);
10811 	}
10812 
10813 	/* See if command is on the list */
10814 	for (i = 0; i < ST_NUM_MEMBERS(rcmds); i++) {
10815 		if ((uchar_t)cdb[0] == rcmds[i].cmd) {
10816 			/*
10817 			 * cmd is on list.
10818 			 * if byte is zero always allowed.
10819 			 */
10820 			if (rcmds[i].byte == 0) {
10821 				return (rval);
10822 			}
10823 			if (((cdb[rcmds[i].byte]) & (rcmds[i].mask)) == 0) {
10824 				return (rval);
10825 			}
10826 			break;
10827 		}
10828 	}
10829 
10830 	ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
10831 	    "Command %s requires reservation", st_print_scsi_cmd(cdb[0]));
10832 
10833 	rval = st_do_reserve(un);
10834 
10835 	return (rval);
10836 }
10837 
10838 static int
10839 st_check_cmd_for_need_to_reserve(struct scsi_tape *un, uchar_t cmd, int cnt)
10840 {
10841 	int i;
10842 	int rval = 0;
10843 
10844 	ST_FUNC(ST_DEVINFO, st_check_cmd_for_need_to_reserve);
10845 
10846 	if ((un->un_rsvd_status & (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) ||
10847 	    (un->un_dp->options & ST_NO_RESERVE_RELEASE)) {
10848 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
10849 		    "st_check_cmd_for_need_to_reserve() reserve unneeded %s",
10850 		    st_print_scsi_cmd(cmd));
10851 		return (0);
10852 	}
10853 
10854 	/* See if command is on the list */
10855 	for (i = 0; i < ST_NUM_MEMBERS(rcmds); i++) {
10856 		if (cmd == rcmds[i].cmd) {
10857 			/*
10858 			 * cmd is on list.
10859 			 * if byte is zero always allowed.
10860 			 */
10861 			if (rcmds[i].byte == 0) {
10862 				return (rval);
10863 			}
10864 			if (((rcmds[i].mask) & cnt) == 0) {
10865 				return (rval);
10866 			}
10867 			break;
10868 		}
10869 	}
10870 
10871 	ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
10872 	    "Cmd %s requires reservation", st_print_scsi_cmd(cmd));
10873 
10874 	rval = st_do_reserve(un);
10875 
10876 	return (rval);
10877 }
10878 
10879 static int
10880 st_reserve_release(struct scsi_tape *un, int cmd)
10881 {
10882 	struct uscsi_cmd	uscsi_cmd;
10883 	struct uscsi_cmd	*com = &uscsi_cmd;
10884 	int			rval;
10885 	char			cdb[CDB_GROUP0];
10886 
10887 
10888 
10889 	ST_FUNC(ST_DEVINFO, st_reserve_release);
10890 
10891 	ASSERT(mutex_owned(ST_MUTEX));
10892 
10893 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10894 	    "st_reserve_release: %s \n",
10895 	    (cmd == ST_RELEASE)?  "Releasing":"Reserving");
10896 
10897 	bzero(cdb, CDB_GROUP0);
10898 	if (cmd == ST_RELEASE) {
10899 		cdb[0] = SCMD_RELEASE;
10900 	} else {
10901 		cdb[0] = SCMD_RESERVE;
10902 	}
10903 	bzero(com, sizeof (struct uscsi_cmd));
10904 	com->uscsi_flags = USCSI_WRITE;
10905 	com->uscsi_cdb = cdb;
10906 	com->uscsi_cdblen = CDB_GROUP0;
10907 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
10908 
10909 	rval = st_ioctl_cmd(un->un_dev, com, FKIOCTL);
10910 
10911 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10912 	    "st_reserve_release: rval(1)=%d\n", rval);
10913 
10914 	if (rval) {
10915 		if (com->uscsi_status == STATUS_RESERVATION_CONFLICT) {
10916 			rval = EACCES;
10917 		}
10918 		/*
10919 		 * dynamically turn off reserve/release support
10920 		 * in case of drives which do not support
10921 		 * reserve/release command(ATAPI drives).
10922 		 */
10923 		if (un->un_status == KEY_ILLEGAL_REQUEST) {
10924 			if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
10925 				un->un_dp->options |= ST_NO_RESERVE_RELEASE;
10926 				ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10927 				    "Tape unit does not support "
10928 				    "reserve/release \n");
10929 			}
10930 			rval = 0;
10931 		}
10932 	}
10933 	return (rval);
10934 }
10935 
10936 static int
10937 st_take_ownership(dev_t dev)
10938 {
10939 	int rval;
10940 
10941 	GET_SOFT_STATE(dev);
10942 
10943 	ST_FUNC(ST_DEVINFO, st_take_ownership);
10944 
10945 	ASSERT(mutex_owned(ST_MUTEX));
10946 
10947 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10948 	    "st_take_ownership: Entering ...\n");
10949 
10950 
10951 	rval = st_reserve_release(un, ST_RESERVE);
10952 	/*
10953 	 * XXX -> Should reset be done only if we get EACCES.
10954 	 * .
10955 	 */
10956 	if (rval) {
10957 		mutex_exit(ST_MUTEX);
10958 		if (scsi_reset(ROUTE, RESET_TARGET) == 0) {
10959 			if (scsi_reset(ROUTE, RESET_ALL) == 0) {
10960 				mutex_enter(ST_MUTEX);
10961 				return (EIO);
10962 			}
10963 		}
10964 		mutex_enter(ST_MUTEX);
10965 		un->un_rsvd_status &=
10966 		    ~(ST_LOST_RESERVE | ST_RESERVATION_CONFLICT);
10967 
10968 		mutex_exit(ST_MUTEX);
10969 		delay(drv_usectohz(ST_RESERVATION_DELAY));
10970 		mutex_enter(ST_MUTEX);
10971 		/*
10972 		 * remove the check condition.
10973 		 */
10974 		(void) st_reserve_release(un, ST_RESERVE);
10975 		if ((rval = st_reserve_release(un, ST_RESERVE)) != 0) {
10976 			if ((st_reserve_release(un, ST_RESERVE)) != 0) {
10977 				rval = (un->un_rsvd_status &
10978 				    ST_RESERVATION_CONFLICT) ? EACCES : EIO;
10979 				return (rval);
10980 			}
10981 		}
10982 		/*
10983 		 * Set tape state to ST_STATE_OFFLINE , in case if
10984 		 * the user wants to continue and start using
10985 		 * the tape.
10986 		 */
10987 		un->un_state = ST_STATE_OFFLINE;
10988 		un->un_rsvd_status |= ST_INIT_RESERVE;
10989 	}
10990 	return (rval);
10991 }
10992 
10993 static int
10994 st_create_errstats(struct scsi_tape *un, int instance)
10995 {
10996 	char	kstatname[KSTAT_STRLEN];
10997 
10998 	ST_FUNC(ST_DEVINFO, st_create_errstats);
10999 
11000 	/*
11001 	 * Create device error kstats
11002 	 */
11003 
11004 	if (un->un_errstats == (kstat_t *)0) {
11005 		(void) sprintf(kstatname, "st%d,err", instance);
11006 		un->un_errstats = kstat_create("sterr", instance, kstatname,
11007 		    "device_error", KSTAT_TYPE_NAMED,
11008 		    sizeof (struct st_errstats) / sizeof (kstat_named_t),
11009 		    KSTAT_FLAG_PERSISTENT);
11010 
11011 		if (un->un_errstats) {
11012 			struct st_errstats	*stp;
11013 
11014 			stp = (struct st_errstats *)un->un_errstats->ks_data;
11015 			kstat_named_init(&stp->st_softerrs, "Soft Errors",
11016 			    KSTAT_DATA_ULONG);
11017 			kstat_named_init(&stp->st_harderrs, "Hard Errors",
11018 			    KSTAT_DATA_ULONG);
11019 			kstat_named_init(&stp->st_transerrs, "Transport Errors",
11020 			    KSTAT_DATA_ULONG);
11021 			kstat_named_init(&stp->st_vid, "Vendor",
11022 			    KSTAT_DATA_CHAR);
11023 			kstat_named_init(&stp->st_pid, "Product",
11024 			    KSTAT_DATA_CHAR);
11025 			kstat_named_init(&stp->st_revision, "Revision",
11026 			    KSTAT_DATA_CHAR);
11027 			kstat_named_init(&stp->st_serial, "Serial No",
11028 			    KSTAT_DATA_CHAR);
11029 			un->un_errstats->ks_private = un;
11030 			un->un_errstats->ks_update = nulldev;
11031 			kstat_install(un->un_errstats);
11032 			/*
11033 			 * Fill in the static data
11034 			 */
11035 			(void) strncpy(&stp->st_vid.value.c[0],
11036 			    ST_INQUIRY->inq_vid, 8);
11037 			/*
11038 			 * XXX:  Emulex MT-02 (and emulators) predates
11039 			 *	 SCSI-1 and has no vid & pid inquiry data.
11040 			 */
11041 			if (ST_INQUIRY->inq_len != 0) {
11042 				(void) strncpy(&stp->st_pid.value.c[0],
11043 				    ST_INQUIRY->inq_pid, 16);
11044 				(void) strncpy(&stp->st_revision.value.c[0],
11045 				    ST_INQUIRY->inq_revision, 4);
11046 				(void) strncpy(&stp->st_serial.value.c[0],
11047 				    ST_INQUIRY->inq_serial, 12);
11048 			}
11049 		}
11050 	}
11051 	return (0);
11052 }
11053 
11054 static int
11055 st_validate_tapemarks(struct scsi_tape *un, tapepos_t *pos)
11056 {
11057 	dev_t dev;
11058 	int rval;
11059 
11060 	ST_FUNC(ST_DEVINFO, st_validate_tapemarks);
11061 
11062 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
11063 	ASSERT(mutex_owned(ST_MUTEX));
11064 
11065 	/* Can't restore an invalid position */
11066 	if (pos->pmode == invalid) {
11067 		return (4);
11068 	}
11069 
11070 	/*
11071 	 * Assumtions:
11072 	 *	If a position was read and is in logical position mode.
11073 	 *	If a drive supports read position it supports locate.
11074 	 *	If the read position type is not NO_POS. even though
11075 	 *	   a read position make not have been attemped yet.
11076 	 *
11077 	 *	The drive can locate to the position.
11078 	 */
11079 	if (pos->pmode == logical || un->un_read_pos_type != NO_POS) {
11080 		/*
11081 		 * If position mode is logical or legacy mode try
11082 		 * to locate there as it is faster.
11083 		 * If it fails try the old way.
11084 		 */
11085 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
11086 		    "Restoring tape position to lgclblkbo=0x%"PRIx64"....",
11087 		    pos->lgclblkno);
11088 
11089 		if (st_logical_block_locate(un, pos->lgclblkno, pos->partition)
11090 		    == 0) {
11091 			/* Assume we are there copy rest of position back */
11092 			if (un->un_pos.lgclblkno == pos->lgclblkno) {
11093 				COPY_POS(&un->un_pos, pos);
11094 			}
11095 			return (0);
11096 		}
11097 
11098 		/*
11099 		 * If logical block locate failed to restore a logical
11100 		 * position, can't recover.
11101 		 */
11102 		if (pos->pmode == logical) {
11103 			return (-1);
11104 		}
11105 	}
11106 
11107 	dev = un->un_dev;
11108 
11109 	scsi_log(ST_DEVINFO, st_label, CE_NOTE,
11110 	    "Restoring tape position at fileno=%x, blkno=%x....",
11111 	    pos->fileno, pos->blkno);
11112 
11113 	/*
11114 	 * Rewind ? Oh yeah, Fidelity has got the STK F/W changed
11115 	 * so as not to rewind tape on RESETS: Gee, Has life ever
11116 	 * been simple in tape land ?
11117 	 */
11118 	rval = st_cmd(dev, SCMD_REWIND, 0, SYNC_CMD);
11119 	if (rval) {
11120 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
11121 		"Failed to restore the last file and block position: In"
11122 		" this state, Tape will be loaded at BOT during next open");
11123 		un->un_pos.pmode = invalid;
11124 		return (rval);
11125 	}
11126 
11127 	/* If the position was as the result of back space file */
11128 	if (pos->blkno > (INF / 2)) {
11129 		/* Go one extra file forward */
11130 		pos->fileno++;
11131 		/* Figure how many blocks to back into the previous file */
11132 		pos->blkno = -(INF - pos->blkno);
11133 	}
11134 
11135 	/* Go to requested fileno */
11136 	if (pos->fileno) {
11137 		rval = st_cmd(dev, SCMD_SPACE, Fmk(pos->fileno), SYNC_CMD);
11138 		if (rval) {
11139 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
11140 			    "Failed to restore the last file position: In this "
11141 			    " state, Tape will be loaded at BOT during next"
11142 			    " open %d", __LINE__);
11143 			un->un_pos.pmode = invalid;
11144 			pos->pmode = invalid;
11145 			return (rval);
11146 		}
11147 	}
11148 
11149 	/*
11150 	 * If backing into a file we already did an extra file forward.
11151 	 * Now we have to back over the filemark to get to the end of
11152 	 * the previous file. The blkno has been ajusted to a negative
11153 	 * value so we will get to the expected location.
11154 	 */
11155 	if (pos->blkno) {
11156 		rval = st_cmd(dev, SCMD_SPACE, Fmk(-1), SYNC_CMD);
11157 		if (rval) {
11158 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
11159 			    "Failed to restore the last file position: In this "
11160 			    " state, Tape will be loaded at BOT during next"
11161 			    " open %d", __LINE__);
11162 			un->un_pos.pmode = invalid;
11163 			pos->pmode = invalid;
11164 			return (rval);
11165 		}
11166 	}
11167 
11168 	/*
11169 	 * The position mode, block and fileno should be correct,
11170 	 * This updates eof and logical position information.
11171 	 */
11172 	un->un_pos.eof = pos->eof;
11173 	un->un_pos.lgclblkno = pos->lgclblkno;
11174 
11175 	return (0);
11176 }
11177 
11178 /*
11179  * check sense key, ASC, ASCQ in order to determine if the tape needs
11180  * to be ejected
11181  */
11182 
11183 static int
11184 st_check_asc_ascq(struct scsi_tape *un)
11185 {
11186 	struct scsi_extended_sense *sensep = ST_RQSENSE;
11187 	struct tape_failure_code   *code;
11188 
11189 	ST_FUNC(ST_DEVINFO, st_check_asc_ascq);
11190 
11191 	for (code = st_tape_failure_code; code->key != 0xff; code++) {
11192 		if ((code->key  == sensep->es_key) &&
11193 		    (code->add_code  == sensep->es_add_code) &&
11194 		    (code->qual_code == sensep->es_qual_code))
11195 			return (1);
11196 	}
11197 	return (0);
11198 }
11199 
11200 /*
11201  * st_logpage_supported() sends a Log Sense command with
11202  * page code = 0 = Supported Log Pages Page to the device,
11203  * to see whether the page 'page' is supported.
11204  * Return values are:
11205  * -1 if the Log Sense command fails
11206  * 0 if page is not supported
11207  * 1 if page is supported
11208  */
11209 
11210 static int
11211 st_logpage_supported(dev_t dev, uchar_t page)
11212 {
11213 	uchar_t *sp, *sensep;
11214 	unsigned length;
11215 	struct uscsi_cmd *com;
11216 	int rval;
11217 	char cdb[CDB_GROUP1] = {
11218 		SCMD_LOG_SENSE_G1,
11219 		0,
11220 		SUPPORTED_LOG_PAGES_PAGE,
11221 		0,
11222 		0,
11223 		0,
11224 		0,
11225 		0,
11226 		(char)LOG_SENSE_LENGTH,
11227 		0
11228 	};
11229 
11230 	GET_SOFT_STATE(dev);
11231 
11232 	ST_FUNC(ST_DEVINFO, st_logpage_supported);
11233 
11234 	ASSERT(mutex_owned(ST_MUTEX));
11235 
11236 	com = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
11237 	sensep = kmem_zalloc(LOG_SENSE_LENGTH, KM_SLEEP);
11238 
11239 	com->uscsi_cdb = cdb;
11240 	com->uscsi_cdblen = CDB_GROUP1;
11241 	com->uscsi_bufaddr = (caddr_t)sensep;
11242 	com->uscsi_buflen = LOG_SENSE_LENGTH;
11243 	com->uscsi_flags =
11244 	    USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
11245 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
11246 	rval = st_ioctl_cmd(dev, com, FKIOCTL);
11247 	if (rval || com->uscsi_status) {
11248 		/* uscsi-command failed */
11249 		rval = -1;
11250 	} else {
11251 
11252 		sp = sensep + 3;
11253 
11254 		for (length = *sp++; length > 0; length--, sp++) {
11255 
11256 			if (*sp == page) {
11257 				rval = 1;
11258 				break;
11259 			}
11260 		}
11261 	}
11262 	kmem_free(com, sizeof (struct uscsi_cmd));
11263 	kmem_free(sensep, LOG_SENSE_LENGTH);
11264 	return (rval);
11265 }
11266 
11267 
11268 /*
11269  * st_check_clean_bit() gets the status of the tape's cleaning bit.
11270  *
11271  * If the device does support the TapeAlert log page, then the cleaning bit
11272  * information will be read from this page. Otherwise we will see if one of
11273  * ST_CLN_TYPE_1, ST_CLN_TYPE_2 or ST_CLN_TYPE_3 is set in the properties of
11274  * the device, which means, that we can get the cleaning bit information via
11275  * a RequestSense command.
11276  * If both methods of getting cleaning bit information are not supported
11277  * st_check_clean_bit() will return with 0. Otherwise st_check_clean_bit()
11278  * returns with
11279  * - MTF_TAPE_CLN_SUPPORTED if cleaning bit is not set or
11280  * - MTF_TAPE_CLN_SUPPORTED | MTF_TAPE_HEAD_DIRTY if cleaning bit is set.
11281  * If the call to st_ioctl_cmd() to do the Log Sense or the Request Sense
11282  * command fails, or if the amount of Request Sense data is not enough, then
11283  *  st_check_clean_bit() returns with -1.
11284  */
11285 
11286 static int
11287 st_check_clean_bit(dev_t dev)
11288 {
11289 	int rval = 0;
11290 
11291 	GET_SOFT_STATE(dev);
11292 
11293 	ST_FUNC(ST_DEVINFO, st_check_clean_bit);
11294 
11295 	ASSERT(mutex_owned(ST_MUTEX));
11296 
11297 	if (un->un_HeadClean & TAPE_ALERT_NOT_SUPPORTED) {
11298 		return (rval);
11299 	}
11300 
11301 	if (un->un_HeadClean == TAPE_ALERT_SUPPORT_UNKNOWN) {
11302 
11303 		rval = st_logpage_supported(dev, TAPE_SEQUENTIAL_PAGE);
11304 		if (rval == 1) {
11305 
11306 			un->un_HeadClean |= TAPE_SEQUENTIAL_SUPPORTED;
11307 		}
11308 
11309 		rval = st_logpage_supported(dev, TAPE_ALERT_PAGE);
11310 		if (rval == 1) {
11311 
11312 			un->un_HeadClean |= TAPE_ALERT_SUPPORTED;
11313 		}
11314 
11315 		if (un->un_HeadClean == TAPE_ALERT_SUPPORT_UNKNOWN) {
11316 
11317 			un->un_HeadClean = TAPE_ALERT_NOT_SUPPORTED;
11318 		}
11319 	}
11320 
11321 	rval = 0;
11322 
11323 	if (un->un_HeadClean & TAPE_SEQUENTIAL_SUPPORTED) {
11324 
11325 		rval = st_check_sequential_clean_bit(dev);
11326 	}
11327 
11328 	if ((rval <= 0) && (un->un_HeadClean & TAPE_ALERT_SUPPORTED)) {
11329 
11330 		rval = st_check_alert_flags(dev);
11331 	}
11332 
11333 	if ((rval <= 0) && (un->un_dp->options & ST_CLN_MASK)) {
11334 
11335 		rval = st_check_sense_clean_bit(dev);
11336 	}
11337 
11338 	if (rval < 0) {
11339 		return (rval);
11340 	}
11341 
11342 	/*
11343 	 * If found a supported means to check need to clean.
11344 	 */
11345 	if (rval & MTF_TAPE_CLN_SUPPORTED) {
11346 
11347 		/*
11348 		 * head needs to be cleaned.
11349 		 */
11350 		if (rval & MTF_TAPE_HEAD_DIRTY) {
11351 
11352 			/*
11353 			 * Print log message only first time
11354 			 * found needing cleaned.
11355 			 */
11356 			if ((un->un_HeadClean & TAPE_PREVIOUSLY_DIRTY) == 0) {
11357 
11358 				scsi_log(ST_DEVINFO, st_label, CE_WARN,
11359 				    "Periodic head cleaning required");
11360 
11361 				un->un_HeadClean |= TAPE_PREVIOUSLY_DIRTY;
11362 			}
11363 
11364 		} else {
11365 
11366 			un->un_HeadClean &= ~TAPE_PREVIOUSLY_DIRTY;
11367 		}
11368 	}
11369 
11370 	return (rval);
11371 }
11372 
11373 
11374 static int
11375 st_check_sequential_clean_bit(dev_t dev)
11376 {
11377 	int rval;
11378 	int ix;
11379 	ushort_t parameter;
11380 	struct uscsi_cmd *cmd;
11381 	struct log_sequential_page *sp;
11382 	struct log_sequential_page_parameter *prm;
11383 	char cdb[CDB_GROUP1] = {
11384 		SCMD_LOG_SENSE_G1,
11385 		0,
11386 		TAPE_SEQUENTIAL_PAGE | CURRENT_CUMULATIVE_VALUES,
11387 		0,
11388 		0,
11389 		0,
11390 		0,
11391 		(char)(sizeof (struct log_sequential_page) >> 8),
11392 		(char)(sizeof (struct log_sequential_page)),
11393 		0
11394 	};
11395 
11396 	GET_SOFT_STATE(dev);
11397 
11398 	ST_FUNC(ST_DEVINFO, st_check_sequential_clean_bit);
11399 
11400 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
11401 	sp  = kmem_zalloc(sizeof (struct log_sequential_page), KM_SLEEP);
11402 
11403 	cmd->uscsi_flags   =
11404 	    USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
11405 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
11406 	cmd->uscsi_cdb	   = cdb;
11407 	cmd->uscsi_cdblen  = CDB_GROUP1;
11408 	cmd->uscsi_bufaddr = (caddr_t)sp;
11409 	cmd->uscsi_buflen  = sizeof (struct log_sequential_page);
11410 
11411 	rval = st_ioctl_cmd(dev, cmd, FKIOCTL);
11412 
11413 	if (rval || cmd->uscsi_status || cmd->uscsi_resid) {
11414 
11415 		rval = -1;
11416 
11417 	} else if (sp->log_page.code != TAPE_SEQUENTIAL_PAGE) {
11418 
11419 		rval = -1;
11420 	}
11421 
11422 	prm = &sp->param[0];
11423 
11424 	for (ix = 0; rval == 0 && ix < TAPE_SEQUENTIAL_PAGE_PARA; ix++) {
11425 
11426 		if (prm->log_param.length == 0) {
11427 			break;
11428 		}
11429 
11430 		parameter = (((prm->log_param.pc_hi << 8) & 0xff00) +
11431 		    (prm->log_param.pc_lo & 0xff));
11432 
11433 		if (parameter == SEQUENTIAL_NEED_CLN) {
11434 
11435 			rval = MTF_TAPE_CLN_SUPPORTED;
11436 			if (prm->param_value[prm->log_param.length - 1]) {
11437 
11438 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11439 				    "sequential log says head dirty\n");
11440 				rval |= MTF_TAPE_HEAD_DIRTY;
11441 			}
11442 		}
11443 		prm = (struct log_sequential_page_parameter *)
11444 		    &prm->param_value[prm->log_param.length];
11445 	}
11446 
11447 	kmem_free(cmd, sizeof (struct uscsi_cmd));
11448 	kmem_free(sp,  sizeof (struct log_sequential_page));
11449 
11450 	return (rval);
11451 }
11452 
11453 
11454 static int
11455 st_check_alert_flags(dev_t dev)
11456 {
11457 	struct st_tape_alert *ta;
11458 	struct uscsi_cmd *com;
11459 	unsigned ix, length;
11460 	int rval;
11461 	tape_alert_flags flag;
11462 	char cdb[CDB_GROUP1] = {
11463 		SCMD_LOG_SENSE_G1,
11464 		0,
11465 		TAPE_ALERT_PAGE | CURRENT_THRESHOLD_VALUES,
11466 		0,
11467 		0,
11468 		0,
11469 		0,
11470 		(char)(sizeof (struct st_tape_alert) >> 8),
11471 		(char)(sizeof (struct st_tape_alert)),
11472 		0
11473 	};
11474 
11475 	GET_SOFT_STATE(dev);
11476 
11477 	ST_FUNC(ST_DEVINFO, st_check_alert_clean_bit);
11478 
11479 	com = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
11480 	ta  = kmem_zalloc(sizeof (struct st_tape_alert), KM_SLEEP);
11481 
11482 	com->uscsi_cdb = cdb;
11483 	com->uscsi_cdblen = CDB_GROUP1;
11484 	com->uscsi_bufaddr = (caddr_t)ta;
11485 	com->uscsi_buflen = sizeof (struct st_tape_alert);
11486 	com->uscsi_flags =
11487 	    USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
11488 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
11489 
11490 	rval = st_ioctl_cmd(dev, com, FKIOCTL);
11491 
11492 	if (rval || com->uscsi_status || com->uscsi_resid) {
11493 
11494 		rval = -1; /* uscsi-command failed */
11495 
11496 	} else if (ta->log_page.code != TAPE_ALERT_PAGE) {
11497 
11498 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11499 		"Not Alert Log Page returned 0x%X\n", ta->log_page.code);
11500 		rval = -1;
11501 	}
11502 
11503 	length = (ta->log_page.length_hi << 8) + ta->log_page.length_lo;
11504 
11505 
11506 	if (length != TAPE_ALERT_PARAMETER_LENGTH) {
11507 
11508 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11509 		    "TapeAlert length %d\n", length);
11510 	}
11511 
11512 
11513 	for (ix = 0; ix < TAPE_ALERT_MAX_PARA; ix++) {
11514 
11515 		/*
11516 		 * if rval is bad before the first pass don't bother
11517 		 */
11518 		if (ix == 0 && rval != 0) {
11519 
11520 			break;
11521 		}
11522 
11523 		flag = ((ta->param[ix].log_param.pc_hi << 8) +
11524 		    ta->param[ix].log_param.pc_lo);
11525 
11526 		if ((ta->param[ix].param_value & 1) == 0) {
11527 			continue;
11528 		}
11529 		/*
11530 		 * check to see if current parameter is of interest.
11531 		 * CLEAN_FOR_ERRORS is vendor specific to 9840 9940 stk's.
11532 		 */
11533 		if ((flag == TAF_CLEAN_NOW) ||
11534 		    (flag == TAF_CLEAN_PERIODIC) ||
11535 		    ((flag == CLEAN_FOR_ERRORS) &&
11536 		    (un->un_dp->type == ST_TYPE_STK9840))) {
11537 
11538 			rval = MTF_TAPE_CLN_SUPPORTED;
11539 
11540 
11541 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11542 			    "alert_page drive needs clean %d\n", flag);
11543 			un->un_HeadClean |= TAPE_ALERT_STILL_DIRTY;
11544 			rval |= MTF_TAPE_HEAD_DIRTY;
11545 
11546 		} else if (flag == TAF_CLEANING_MEDIA) {
11547 
11548 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11549 			    "alert_page drive was cleaned\n");
11550 			un->un_HeadClean &= ~TAPE_ALERT_STILL_DIRTY;
11551 		}
11552 
11553 	}
11554 
11555 	/*
11556 	 * Report it as dirty till we see it cleaned
11557 	 */
11558 	if (un->un_HeadClean & TAPE_ALERT_STILL_DIRTY) {
11559 
11560 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11561 		    "alert_page still dirty\n");
11562 		rval |= MTF_TAPE_HEAD_DIRTY;
11563 	}
11564 
11565 	kmem_free(com, sizeof (struct uscsi_cmd));
11566 	kmem_free(ta,  sizeof (struct st_tape_alert));
11567 
11568 	return (rval);
11569 }
11570 
11571 
11572 static int
11573 st_check_sense_clean_bit(dev_t dev)
11574 {
11575 	uchar_t *sensep;
11576 	char cdb[CDB_GROUP0];
11577 	struct uscsi_cmd *com;
11578 	ushort_t byte_pos;
11579 	uchar_t bit_mask;
11580 	unsigned length;
11581 	int index;
11582 	int rval;
11583 
11584 	GET_SOFT_STATE(dev);
11585 
11586 	ST_FUNC(ST_DEVINFO, st_check_sense_clean_bit);
11587 
11588 	/*
11589 	 * Since this tape does not support Tape Alert,
11590 	 * we now try to get the cleanbit status via
11591 	 * Request Sense.
11592 	 */
11593 
11594 	if ((un->un_dp->options & ST_CLN_MASK) == ST_CLN_TYPE_1) {
11595 
11596 		index = 0;
11597 
11598 	} else if ((un->un_dp->options & ST_CLN_MASK) == ST_CLN_TYPE_2) {
11599 
11600 		index = 1;
11601 
11602 	} else if ((un->un_dp->options & ST_CLN_MASK) == ST_CLN_TYPE_3) {
11603 
11604 		index = 2;
11605 
11606 	} else {
11607 
11608 		return (-1);
11609 	}
11610 
11611 	byte_pos  = st_cln_bit_position[index].cln_bit_byte;
11612 	bit_mask  = st_cln_bit_position[index].cln_bit_mask;
11613 	length = byte_pos + 1;
11614 
11615 	com    = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
11616 	sensep = kmem_zalloc(length, KM_SLEEP);
11617 
11618 	cdb[0] = SCMD_REQUEST_SENSE;
11619 	cdb[1] = 0;
11620 	cdb[2] = 0;
11621 	cdb[3] = 0;
11622 	cdb[4] = (char)length;
11623 	cdb[5] = 0;
11624 
11625 	com->uscsi_cdb = cdb;
11626 	com->uscsi_cdblen = CDB_GROUP0;
11627 	com->uscsi_bufaddr = (caddr_t)sensep;
11628 	com->uscsi_buflen = length;
11629 	com->uscsi_flags =
11630 	    USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
11631 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
11632 
11633 	rval = st_ioctl_cmd(dev, com, FKIOCTL);
11634 
11635 	if (rval || com->uscsi_status || com->uscsi_resid) {
11636 
11637 		rval = -1;
11638 
11639 	} else {
11640 
11641 		rval = MTF_TAPE_CLN_SUPPORTED;
11642 		if ((sensep[byte_pos] & bit_mask) == bit_mask) {
11643 
11644 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11645 			    "sense data says head dirty\n");
11646 			rval |= MTF_TAPE_HEAD_DIRTY;
11647 		}
11648 	}
11649 
11650 	kmem_free(com, sizeof (struct uscsi_cmd));
11651 	kmem_free(sensep, length);
11652 	return (rval);
11653 }
11654 
11655 /*
11656  * st_clear_unit_attention
11657  *
11658  *  	run test unit ready's to clear out outstanding
11659  * 	unit attentions.
11660  * 	returns zero for SUCCESS or the errno from st_cmd call
11661  */
11662 static int
11663 st_clear_unit_attentions(dev_t dev_instance, int max_trys)
11664 {
11665 	int	i    = 0;
11666 	int	rval;
11667 
11668 #ifdef DEBUG
11669 	GET_SOFT_STATE(dev_instance);
11670 	ST_FUNC(ST_DEVINFO, st_clear_unit_attentions);
11671 #endif
11672 
11673 	do {
11674 		rval = st_cmd(dev_instance, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
11675 	} while ((rval != 0) && (rval != ENXIO) && (++i < max_trys));
11676 	return (rval);
11677 }
11678 
11679 static void
11680 st_calculate_timeouts(struct scsi_tape *un)
11681 {
11682 	ST_FUNC(ST_DEVINFO, st_calculate_timeouts);
11683 
11684 	if (un->un_dp->non_motion_timeout == 0) {
11685 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
11686 			un->un_dp->non_motion_timeout =
11687 			    st_io_time * st_long_timeout_x;
11688 		} else {
11689 			un->un_dp->non_motion_timeout = (ushort_t)st_io_time;
11690 		}
11691 	}
11692 
11693 	if (un->un_dp->io_timeout == 0) {
11694 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
11695 			un->un_dp->io_timeout = st_io_time * st_long_timeout_x;
11696 		} else {
11697 			un->un_dp->io_timeout = (ushort_t)st_io_time;
11698 		}
11699 	}
11700 
11701 	if (un->un_dp->rewind_timeout == 0) {
11702 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
11703 			un->un_dp->rewind_timeout =
11704 			    st_space_time * st_long_timeout_x;
11705 		} else {
11706 			un->un_dp->rewind_timeout = (ushort_t)st_space_time;
11707 		}
11708 	}
11709 
11710 	if (un->un_dp->space_timeout == 0) {
11711 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
11712 			un->un_dp->space_timeout =
11713 			    st_space_time * st_long_timeout_x;
11714 		} else {
11715 			un->un_dp->space_timeout = (ushort_t)st_space_time;
11716 		}
11717 	}
11718 
11719 	if (un->un_dp->load_timeout == 0) {
11720 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
11721 			un->un_dp->load_timeout =
11722 			    st_space_time * st_long_timeout_x;
11723 		} else {
11724 			un->un_dp->load_timeout = (ushort_t)st_space_time;
11725 		}
11726 	}
11727 
11728 	if (un->un_dp->unload_timeout == 0) {
11729 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
11730 			un->un_dp->unload_timeout =
11731 			    st_space_time * st_long_timeout_x;
11732 		} else {
11733 			un->un_dp->unload_timeout = (ushort_t)st_space_time;
11734 		}
11735 	}
11736 
11737 	if (un->un_dp->erase_timeout == 0) {
11738 		if (un->un_dp->options & ST_LONG_ERASE) {
11739 			un->un_dp->erase_timeout =
11740 			    st_space_time * st_long_space_time_x;
11741 		} else {
11742 			un->un_dp->erase_timeout = (ushort_t)st_space_time;
11743 		}
11744 	}
11745 }
11746 
11747 
11748 static writablity
11749 st_is_not_wormable(struct scsi_tape *un)
11750 {
11751 	ST_FUNC(ST_DEVINFO, st_is_not_wormable);
11752 	return (RDWR);
11753 }
11754 
11755 static writablity
11756 st_is_hp_lto_tape_worm(struct scsi_tape *un)
11757 {
11758 	writablity wrt;
11759 
11760 	ST_FUNC(ST_DEVINFO, st_is_hp_lto_tape_worm);
11761 
11762 	/* Mode sense should be current */
11763 	switch (un->un_mspl->media_type) {
11764 	case 0x00:
11765 		switch (un->un_mspl->density) {
11766 		case 0x40:
11767 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11768 			    "Drive has standard Gen I media loaded\n");
11769 			break;
11770 		case 0x42:
11771 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11772 			    "Drive has standard Gen II media loaded\n");
11773 			break;
11774 		case 0x44:
11775 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11776 			    "Drive has standard Gen III media loaded\n");
11777 			break;
11778 		case 0x46:
11779 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11780 			    "Drive has standard Gen IV media loaded\n");
11781 			break;
11782 		default:
11783 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11784 			    "Drive has standard unknown 0x%X media loaded\n",
11785 			    un->un_mspl->density);
11786 		}
11787 		wrt = RDWR;
11788 		break;
11789 	case 0x01:
11790 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11791 		    "Drive has WORM medium loaded\n");
11792 		wrt = WORM;
11793 		break;
11794 	case 0x80:
11795 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11796 		    "Drive has CD-ROM emulation medium loaded\n");
11797 		wrt = WORM;
11798 		break;
11799 	default:
11800 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11801 		    "Drive has an unexpected medium type 0x%X loaded\n",
11802 		    un->un_mspl->media_type);
11803 		wrt = RDWR;
11804 	}
11805 
11806 	return (wrt);
11807 }
11808 
11809 #define	LTO_REQ_INQUIRY 44
11810 static writablity
11811 st_is_hp_lto_worm(struct scsi_tape *un)
11812 {
11813 	char *buf;
11814 	int result;
11815 	writablity wrt;
11816 
11817 	ST_FUNC(ST_DEVINFO, st_is_hp_lto_worm);
11818 
11819 	buf = kmem_zalloc(LTO_REQ_INQUIRY, KM_SLEEP);
11820 
11821 	result = st_get_special_inquiry(un, LTO_REQ_INQUIRY, buf, 0);
11822 
11823 	if (result != 0) {
11824 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11825 		    "Read Standard Inquiry for WORM support failed");
11826 		wrt = FAILED;
11827 	} else if ((buf[40] & 1) == 0) {
11828 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11829 		    "Drive is NOT WORMable\n");
11830 		/* This drive doesn't support it so don't check again */
11831 		un->un_dp->options &= ~ST_WORMABLE;
11832 		wrt = RDWR;
11833 		un->un_wormable = st_is_not_wormable;
11834 	} else {
11835 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11836 		    "Drive supports WORM version %d\n", buf[40] >> 1);
11837 		un->un_wormable = st_is_hp_lto_tape_worm;
11838 		wrt = un->un_wormable(un);
11839 	}
11840 
11841 	kmem_free(buf, LTO_REQ_INQUIRY);
11842 
11843 	/*
11844 	 * If drive doesn't support it no point in checking further.
11845 	 */
11846 	return (wrt);
11847 }
11848 
11849 static writablity
11850 st_is_t10_worm_device(struct scsi_tape *un)
11851 {
11852 	writablity wrt;
11853 
11854 	ST_FUNC(ST_DEVINFO, st_is_t10_worm_device);
11855 
11856 	if (un->un_mspl->media_type == 0x3c) {
11857 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11858 		    "Drive has WORM media loaded\n");
11859 		wrt = WORM;
11860 	} else {
11861 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11862 		    "Drive has non WORM media loaded\n");
11863 		wrt = RDWR;
11864 	}
11865 	return (wrt);
11866 }
11867 
11868 #define	SEQ_CAP_PAGE	(char)0xb0
11869 static writablity
11870 st_is_t10_worm(struct scsi_tape *un)
11871 {
11872 	char *buf;
11873 	int result;
11874 	writablity wrt;
11875 
11876 	ST_FUNC(ST_DEVINFO, st_is_t10_worm);
11877 
11878 	buf = kmem_zalloc(6, KM_SLEEP);
11879 
11880 	result = st_get_special_inquiry(un, 6, buf, SEQ_CAP_PAGE);
11881 
11882 	if (result != 0) {
11883 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11884 		    "Read Vitial Inquiry for Sequental Capability"
11885 		    " WORM support failed %x", result);
11886 		wrt = FAILED;
11887 	} else if ((buf[4] & 1) == 0) {
11888 		ASSERT(buf[1] == SEQ_CAP_PAGE);
11889 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11890 		    "Drive is NOT WORMable\n");
11891 		/* This drive doesn't support it so don't check again */
11892 		un->un_dp->options &= ~ST_WORMABLE;
11893 		wrt = RDWR;
11894 		un->un_wormable = st_is_not_wormable;
11895 	} else {
11896 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11897 		    "Drive supports WORM\n");
11898 		un->un_wormable = st_is_t10_worm_device;
11899 		wrt = un->un_wormable(un);
11900 	}
11901 
11902 	kmem_free(buf, 6);
11903 
11904 	return (wrt);
11905 }
11906 
11907 
11908 #define	STK_REQ_SENSE 26
11909 
11910 static writablity
11911 st_is_stk_worm(struct scsi_tape *un)
11912 {
11913 	char cdb[CDB_GROUP0] = {SCMD_REQUEST_SENSE, 0, 0, 0, STK_REQ_SENSE, 0};
11914 	struct scsi_extended_sense *sense;
11915 	struct uscsi_cmd *cmd;
11916 	char *buf;
11917 	int result;
11918 	writablity wrt;
11919 
11920 	ST_FUNC(ST_DEVINFO, st_is_stk_worm);
11921 
11922 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
11923 	buf = kmem_alloc(STK_REQ_SENSE, KM_SLEEP);
11924 	sense = (struct scsi_extended_sense *)buf;
11925 
11926 	cmd->uscsi_flags = USCSI_READ;
11927 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
11928 	cmd->uscsi_cdb = &cdb[0];
11929 	cmd->uscsi_bufaddr = buf;
11930 	cmd->uscsi_buflen = STK_REQ_SENSE;
11931 	cmd->uscsi_cdblen = CDB_GROUP0;
11932 	cmd->uscsi_rqlen = 0;
11933 	cmd->uscsi_rqbuf = NULL;
11934 
11935 	result = st_ioctl_cmd(un->un_dev, cmd, FKIOCTL);
11936 
11937 	if (result != 0 || cmd->uscsi_status != 0) {
11938 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11939 		    "Request Sense for WORM failed");
11940 		wrt = RDWR;
11941 	} else if (sense->es_add_len + 8 < 24) {
11942 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11943 		    "Drive didn't send enough sense data for WORM byte %d\n",
11944 		    sense->es_add_len + 8);
11945 		wrt = RDWR;
11946 		un->un_wormable = st_is_not_wormable;
11947 	} else if ((buf[24]) & 0x02) {
11948 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11949 		    "Drive has WORM tape loaded\n");
11950 		wrt = WORM;
11951 		un->un_wormable = st_is_stk_worm;
11952 	} else {
11953 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11954 		    "Drive has normal tape loaded\n");
11955 		wrt = RDWR;
11956 		un->un_wormable = st_is_stk_worm;
11957 	}
11958 
11959 	kmem_free(buf, STK_REQ_SENSE);
11960 	kmem_free(cmd, sizeof (struct uscsi_cmd));
11961 	return (wrt);
11962 }
11963 
11964 #define	DLT_INQ_SZ 44
11965 
11966 static writablity
11967 st_is_dlt_tape_worm(struct scsi_tape *un)
11968 {
11969 	caddr_t buf;
11970 	int result;
11971 	writablity wrt;
11972 
11973 	ST_FUNC(ST_DEVINFO, st_is_dlt_tape_worm);
11974 
11975 	buf = kmem_alloc(DLT_INQ_SZ, KM_SLEEP);
11976 
11977 	/* Read Attribute Media Type */
11978 
11979 	result = st_read_attributes(un, 0x0408, buf, 10);
11980 
11981 	/*
11982 	 * If this quantum drive is attached via an HBA that cannot
11983 	 * support thr read attributes command return error in the
11984 	 * hope that someday they will support the t10 method.
11985 	 */
11986 	if (result == EINVAL && un->un_max_cdb_sz < CDB_GROUP4) {
11987 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
11988 		    "Read Attribute Command for WORM Media detection is not "
11989 		    "supported on the HBA that this drive is attached to.");
11990 		wrt = RDWR;
11991 		un->un_wormable = st_is_not_wormable;
11992 		goto out;
11993 	}
11994 
11995 	if (result != 0) {
11996 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11997 		    "Read Attribute Command for WORM Media returned 0x%x",
11998 		    result);
11999 		wrt = RDWR;
12000 		un->un_dp->options &= ~ST_WORMABLE;
12001 		goto out;
12002 	}
12003 
12004 	if ((uchar_t)buf[9] == 0x80) {
12005 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12006 		    "Drive media is WORM\n");
12007 		wrt = WORM;
12008 	} else {
12009 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12010 		    "Drive media is not WORM Media 0x%x\n", (uchar_t)buf[9]);
12011 		wrt = RDWR;
12012 	}
12013 
12014 out:
12015 	kmem_free(buf, DLT_INQ_SZ);
12016 	return (wrt);
12017 }
12018 
12019 static writablity
12020 st_is_dlt_worm(struct scsi_tape *un)
12021 {
12022 	caddr_t buf;
12023 	int result;
12024 	writablity wrt;
12025 
12026 	ST_FUNC(ST_DEVINFO, st_is_dlt_worm);
12027 
12028 	buf = kmem_alloc(DLT_INQ_SZ, KM_SLEEP);
12029 
12030 	result = st_get_special_inquiry(un, DLT_INQ_SZ, buf, 0xC0);
12031 
12032 	if (result != 0) {
12033 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12034 		    "Read Vendor Specific Inquiry for WORM support failed");
12035 		wrt = RDWR;
12036 		goto out;
12037 	}
12038 
12039 	if ((buf[2] & 1) == 0) {
12040 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12041 		    "Drive is not WORMable\n");
12042 		wrt = RDWR;
12043 		un->un_dp->options &= ~ST_WORMABLE;
12044 		un->un_wormable = st_is_not_wormable;
12045 		goto out;
12046 	} else {
12047 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12048 		    "Drive is WORMable\n");
12049 		un->un_wormable = st_is_dlt_tape_worm;
12050 		wrt = un->un_wormable(un);
12051 	}
12052 out:
12053 	kmem_free(buf, DLT_INQ_SZ);
12054 
12055 	return (wrt);
12056 }
12057 
12058 typedef struct {
12059 	struct modeheader_seq header;
12060 #if defined(_BIT_FIELDS_LTOH) /* X86 */
12061 	uchar_t pagecode	:6,
12062 				:2;
12063 	uchar_t page_len;
12064 	uchar_t syslogalive	:2,
12065 		device		:1,
12066 		abs		:1,
12067 		ulpbot		:1,
12068 		prth		:1,
12069 		ponej		:1,
12070 		ait		:1;
12071 	uchar_t span;
12072 
12073 	uchar_t			:6,
12074 		worm		:1,
12075 		mic		:1;
12076 	uchar_t worm_cap	:1,
12077 				:7;
12078 	uint32_t		:32;
12079 #else /* SPARC */
12080 	uchar_t			:2,
12081 		pagecode	:6;
12082 	uchar_t page_len;
12083 	uchar_t ait		:1,
12084 		device		:1,
12085 		abs		:1,
12086 		ulpbot		:1,
12087 		prth		:1,
12088 		ponej		:1,
12089 		syslogalive	:2;
12090 	uchar_t span;
12091 	uchar_t mic		:1,
12092 		worm		:1,
12093 				:6;
12094 	uchar_t			:7,
12095 		worm_cap	:1;
12096 	uint32_t		:32;
12097 #endif
12098 }ait_dev_con;
12099 
12100 #define	AIT_DEV_PAGE 0x31
12101 static writablity
12102 st_is_sony_worm(struct scsi_tape *un)
12103 {
12104 	int result;
12105 	writablity wrt;
12106 	ait_dev_con *ait_conf;
12107 
12108 	ST_FUNC(ST_DEVINFO, st_is_sony_worm);
12109 
12110 	ait_conf = kmem_zalloc(sizeof (ait_dev_con), KM_SLEEP);
12111 
12112 	result = st_gen_mode_sense(un, AIT_DEV_PAGE,
12113 	    (struct seq_mode *)ait_conf, sizeof (ait_dev_con));
12114 
12115 	if (result == 0) {
12116 
12117 		if (ait_conf->pagecode != AIT_DEV_PAGE) {
12118 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12119 			    "returned page 0x%x not 0x%x AIT_DEV_PAGE\n",
12120 			    ait_conf->pagecode, AIT_DEV_PAGE);
12121 			wrt = RDWR;
12122 			un->un_wormable = st_is_not_wormable;
12123 
12124 		} else if (ait_conf->worm_cap) {
12125 
12126 			un->un_wormable = st_is_sony_worm;
12127 
12128 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12129 			    "Drives is WORMable\n");
12130 			if (ait_conf->worm) {
12131 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12132 				    "Media is WORM\n");
12133 				wrt = WORM;
12134 			} else {
12135 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12136 				    "Media is not WORM\n");
12137 				wrt = RDWR;
12138 			}
12139 
12140 		} else {
12141 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12142 			    "Drives not is WORMable\n");
12143 			wrt = RDWR;
12144 			/* No further checking required */
12145 			un->un_dp->options &= ~ST_WORMABLE;
12146 		}
12147 
12148 	} else {
12149 
12150 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12151 		    "AIT device config mode sense page read command failed"
12152 		    " result = %d ", result);
12153 		wrt = FAILED;
12154 		un->un_wormable = st_is_not_wormable;
12155 	}
12156 
12157 	kmem_free(ait_conf, sizeof (ait_dev_con));
12158 	return (wrt);
12159 }
12160 
12161 static writablity
12162 st_is_drive_worm(struct scsi_tape *un)
12163 {
12164 	writablity wrt;
12165 
12166 	ST_FUNC(ST_DEVINFO, st_is_sony_worm);
12167 
12168 	switch (un->un_dp->type) {
12169 	case MT_ISDLT:
12170 		wrt = st_is_dlt_worm(un);
12171 		break;
12172 
12173 	case MT_ISSTK9840:
12174 		wrt = st_is_stk_worm(un);
12175 		break;
12176 
12177 	case MT_IS8MM:
12178 	case MT_ISAIT:
12179 		wrt = st_is_sony_worm(un);
12180 		break;
12181 
12182 	case MT_LTO:
12183 		if (strncmp("HP ", un->un_dp->vid, 3) == 0) {
12184 			wrt = st_is_hp_lto_worm(un);
12185 		} else {
12186 			wrt = st_is_t10_worm(un);
12187 		}
12188 		break;
12189 
12190 	default:
12191 		wrt = FAILED;
12192 		break;
12193 	}
12194 
12195 	/*
12196 	 * If any of the above failed try the t10 standard method.
12197 	 */
12198 	if (wrt == FAILED) {
12199 		wrt = st_is_t10_worm(un);
12200 	}
12201 
12202 	/*
12203 	 * Unknown method for detecting WORM media.
12204 	 */
12205 	if (wrt == FAILED) {
12206 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12207 		    "Unknown method for WORM media detection\n");
12208 		wrt = RDWR;
12209 		un->un_dp->options &= ~ST_WORMABLE;
12210 	}
12211 
12212 	return (wrt);
12213 }
12214 
12215 static int
12216 st_read_attributes(struct scsi_tape *un, uint16_t attribute, caddr_t buf,
12217     size_t size)
12218 {
12219 	char cdb[CDB_GROUP4];
12220 	int result;
12221 	struct uscsi_cmd *cmd;
12222 
12223 	ST_FUNC(ST_DEVINFO, st_read_attributes);
12224 
12225 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
12226 
12227 	cdb[0] = (char)SCMD_READ_ATTRIBUTE;
12228 	cdb[1] = 0;
12229 	cdb[2] = 0;
12230 	cdb[3] = 0;
12231 	cdb[4] = 0;
12232 	cdb[5] = 0;
12233 	cdb[6] = 0;
12234 	cdb[7] = 0;
12235 	cdb[8] = (char)(attribute >> 8);
12236 	cdb[9] = (char)(attribute);
12237 	cdb[10] = (char)(size >> 24);
12238 	cdb[11] = (char)(size >> 16);
12239 	cdb[12] = (char)(size >> 8);
12240 	cdb[13] = (char)(size);
12241 	cdb[14] = 0;
12242 	cdb[15] = 0;
12243 
12244 
12245 	cmd->uscsi_flags = USCSI_READ | USCSI_DIAGNOSE;
12246 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
12247 	cmd->uscsi_cdb = &cdb[0];
12248 	cmd->uscsi_bufaddr = (caddr_t)buf;
12249 	cmd->uscsi_buflen = size;
12250 	cmd->uscsi_cdblen = sizeof (cdb);
12251 
12252 	result = st_ioctl_cmd(un->un_dev, cmd, FKIOCTL);
12253 
12254 	if (result != 0 || cmd->uscsi_status != 0) {
12255 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12256 		    "st_read_attribute failed: result %d status %d\n",
12257 		    result, cmd->uscsi_status);
12258 		if (result == 0) {
12259 			result = EIO;
12260 		}
12261 		goto exit;
12262 	}
12263 
12264 	/*
12265 	 * The attribute retured should match the attribute requested.
12266 	 */
12267 	if (buf[4] != cdb[8] || buf[5] != cdb[9]) {
12268 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
12269 		    "bad? data", buf, size);
12270 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
12271 		    "st_read_attribute got wrong data back expected 0x%x"
12272 		    " got 0x%x\n", attribute, buf[6] << 8 | buf[7]);
12273 		result = EIO;
12274 	}
12275 exit:
12276 	kmem_free(cmd, sizeof (struct uscsi_cmd));
12277 
12278 	return (result);
12279 }
12280 
12281 static int
12282 st_get_special_inquiry(struct scsi_tape *un, uchar_t size, caddr_t dest,
12283     uchar_t page)
12284 {
12285 	char cdb[CDB_GROUP0];
12286 	struct scsi_extended_sense *sense;
12287 	struct uscsi_cmd *cmd;
12288 	int result;
12289 
12290 	ST_FUNC(ST_DEVINFO, st_get_special_inquiry);
12291 
12292 	cdb[0] = SCMD_INQUIRY;
12293 	cdb[1] = page ? 1 : 0;
12294 	cdb[2] = page;
12295 	cdb[3] = 0;
12296 	cdb[4] = size;
12297 	cdb[5] = 0;
12298 
12299 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
12300 	sense = kmem_alloc(sizeof (struct scsi_extended_sense), KM_SLEEP);
12301 
12302 	cmd->uscsi_flags = USCSI_READ | USCSI_RQENABLE;
12303 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
12304 	cmd->uscsi_cdb = &cdb[0];
12305 	cmd->uscsi_bufaddr = dest;
12306 	cmd->uscsi_buflen = size;
12307 	cmd->uscsi_cdblen = CDB_GROUP0;
12308 	cmd->uscsi_rqlen = sizeof (struct scsi_extended_sense);
12309 	cmd->uscsi_rqbuf = (caddr_t)sense;
12310 
12311 	result = st_ioctl_cmd(un->un_dev, cmd, FKIOCTL);
12312 
12313 	if (result != 0 || cmd->uscsi_status != 0) {
12314 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12315 		    "st_get_special_inquiry() failed for page %x", page);
12316 		if (result == 0) {
12317 			result = EIO;
12318 		}
12319 	}
12320 
12321 	kmem_free(sense, sizeof (struct scsi_extended_sense));
12322 	kmem_free(cmd, sizeof (struct uscsi_cmd));
12323 
12324 	return (result);
12325 }
12326 
12327 
12328 static int
12329 st_update_block_pos(struct scsi_tape *un)
12330 {
12331 	int rval = ENOTTY;
12332 
12333 	ST_FUNC(ST_DEVINFO, st_update_block_pos);
12334 
12335 	while (un->un_read_pos_type != NO_POS) {
12336 		rval = st_cmd(un->un_dev, SCMD_READ_POSITION, 32, SYNC_CMD);
12337 
12338 		if (rval == 0) {
12339 			rval = st_interpret_read_pos(un, un->un_read_pos_type,
12340 			    32, (caddr_t)un->un_read_pos_data);
12341 			break;
12342 		} else if (un->un_status == KEY_UNIT_ATTENTION) {
12343 			continue;
12344 		} else if (un->un_status != KEY_ILLEGAL_REQUEST) {
12345 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
12346 			    "st_update_block_pos() read position cmd %x"
12347 			    " returned %x un_status = %d",
12348 			    un->un_read_pos_type, rval, un->un_status);
12349 			break;
12350 		} else {
12351 			ST_DEBUG4(ST_DEVINFO, st_label, CE_NOTE,
12352 			    "st_update_block_pos() read position cmd %x"
12353 			    " returned %x", un->un_read_pos_type, rval);
12354 		}
12355 
12356 		switch (un->un_read_pos_type) {
12357 		case SHORT_POS:
12358 			un->un_read_pos_type = NO_POS;
12359 			break;
12360 
12361 		case LONG_POS:
12362 			un->un_read_pos_type = EXT_POS;
12363 			break;
12364 
12365 		case EXT_POS:
12366 			un->un_read_pos_type = SHORT_POS;
12367 			break;
12368 
12369 		default:
12370 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
12371 			    "Unexpected read position type 0x%x",
12372 			    un->un_read_pos_type);
12373 		}
12374 	}
12375 
12376 	return (rval);
12377 }
12378 
12379 static int
12380 st_get_read_pos(struct scsi_tape *un, buf_t *bp)
12381 {
12382 	int result;
12383 	size_t d_sz;
12384 	caddr_t pos_info;
12385 	struct uscsi_cmd *cmd = (struct uscsi_cmd *)bp->b_back;
12386 
12387 	ST_FUNC(ST_DEVINFO, st_get_read_pos);
12388 
12389 	if (cmd->uscsi_bufaddr == NULL || cmd->uscsi_buflen <= 0) {
12390 		return (0);
12391 	}
12392 
12393 	if (bp_mapin_common(bp, VM_NOSLEEP) == NULL) {
12394 
12395 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
12396 		    "bp_mapin_common() failed");
12397 
12398 		return (EIO);
12399 	}
12400 
12401 	pos_info = bp->b_un.b_addr;
12402 	d_sz = bp->b_bcount - bp->b_resid;
12403 
12404 #ifdef DEBUG
12405 	if ((st_debug & 0xf) > 2) {
12406 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
12407 		    "st_get_read_pos() position info",
12408 		    pos_info, bp->b_bcount);
12409 	}
12410 #endif
12411 
12412 	result = st_interpret_read_pos(un, cmd->uscsi_cdb[1], d_sz, pos_info);
12413 
12414 	bp_mapout(bp);
12415 
12416 	return (result);
12417 }
12418 
12419 #if defined(_BIG_ENDIAN)
12420 
12421 #define	FIX_ENDIAN32(x)
12422 #define	FIX_ENDIAN64(x)
12423 
12424 #elif defined(_LITTLE_ENDIAN)
12425 
12426 static void
12427 st_swap32(uint32_t *val)
12428 {
12429 	uint32_t tmp;
12430 
12431 	tmp =  (*val >> 24) & 0xff;
12432 	tmp |= (*val >>  8) & 0xff00;
12433 	tmp |= (*val <<  8) & 0xff0000;
12434 	tmp |= (*val << 24) & 0xff000000;
12435 
12436 	*val = tmp;
12437 }
12438 
12439 static void
12440 st_swap64(uint64_t *val)
12441 {
12442 	uint32_t low;
12443 	uint32_t high;
12444 
12445 	low =  (uint32_t)(*val);
12446 	high = (uint32_t)(*val >> 32);
12447 
12448 	st_swap32(&low);
12449 	st_swap32(&high);
12450 
12451 	*val =  high;
12452 	*val |= ((uint64_t)low << 32);
12453 }
12454 
12455 #define	FIX_ENDIAN32(x) st_swap32(x)
12456 #define	FIX_ENDIAN64(x) st_swap64(x)
12457 #endif
12458 
12459 static int
12460 st_interpret_read_pos(struct scsi_tape *un, read_p_types type,
12461     size_t data_sz, caddr_t responce)
12462 {
12463 	int rval = 0;
12464 
12465 	ST_FUNC(ST_DEVINFO, st_interpret_read_pos);
12466 
12467 	/*
12468 	 * Look at byte 1 of cdb to see what kind of read position
12469 	 * was requested.
12470 	 */
12471 	switch (type) {
12472 
12473 	case SHORT_POS: /* Short data format */
12474 	{
12475 		tape_position_t *pos_info = (tape_position_t *)responce;
12476 		uint32_t value;
12477 
12478 		/* If reserved fields are non zero don't use the data */
12479 		if (pos_info->reserved0 || pos_info->reserved1 ||
12480 		    pos_info->reserved2[0] || pos_info->reserved2[1] ||
12481 		    pos_info->reserved3) {
12482 			rval = EIO;
12483 			break;
12484 		}
12485 		/*
12486 		 * Position is to large to use this type of read position.
12487 		 */
12488 		if (pos_info->posi_err == 1) {
12489 			rval = ERANGE;
12490 			break;
12491 		}
12492 
12493 		if (pos_info->blk_posi_unkwn == 0) {
12494 
12495 			if (un->un_pos.partition !=
12496 			    pos_info->partition_number) {
12497 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
12498 				    "SHORT_POS current partition %d read %d\n",
12499 				    un->un_pos.partition,
12500 				    pos_info->partition_number);
12501 			}
12502 			un->un_pos.partition = pos_info->partition_number;
12503 			value = pos_info->host_block;
12504 			FIX_ENDIAN32(&value);
12505 
12506 			if (un->un_pos.lgclblkno != value) {
12507 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
12508 				    "SHORT_POS current logical 0x%"PRIx64" read"
12509 				    " 0x%x\n", un->un_pos.lgclblkno, value);
12510 			}
12511 
12512 			un->un_pos.lgclblkno = (uint64_t)value;
12513 
12514 			if (pos_info->begin_of_part && pos_info->end_of_part) {
12515 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
12516 				    "SHORT_POS returned begin and end of"
12517 				    " partition\n");
12518 				break;
12519 			}
12520 			/* Is drive rewound */
12521 			if ((pos_info->begin_of_part == 1) &&
12522 			    (pos_info->host_block == 0)) {
12523 				un->un_pos.blkno = 0;
12524 				un->un_pos.fileno = 0;
12525 				un->un_pos.pmode = legacy;
12526 			} else if (un->un_pos.pmode == invalid) {
12527 				/* If we were lost now were found */
12528 				un->un_pos.pmode = logical;
12529 			}
12530 		} else {
12531 			un->un_pos.pmode = invalid;
12532 		}
12533 		break;
12534 	}
12535 
12536 	case LONG_POS: /* Long data format */
12537 	{
12538 		uint64_t value;
12539 		tape_position_long_t *long_pos_info =
12540 		    (tape_position_long_t *)responce;
12541 
12542 		/* If reserved fields are non zero don't use the data */
12543 		if ((long_pos_info->reserved0) ||
12544 		    (long_pos_info->reserved1) ||
12545 		    (long_pos_info->reserved2)) {
12546 			rval = EIO;
12547 			break;
12548 		}
12549 
12550 		/* Is position Valid */
12551 		if (long_pos_info->blk_posi_unkwn == 0) {
12552 			uint32_t part;
12553 
12554 			part = long_pos_info->partition;
12555 			FIX_ENDIAN32(&part);
12556 			if (un->un_pos.partition != part) {
12557 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
12558 				    "LONG_POS current partition %d"
12559 				    " read %d\n", un->un_pos.partition, part);
12560 			}
12561 			un->un_pos.partition = part;
12562 			value = long_pos_info->block_number;
12563 			FIX_ENDIAN64(&value);
12564 			if (un->un_pos.lgclblkno != value) {
12565 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
12566 				    "LONG_POS current logical 0x%"PRIx64
12567 				    " read 0x%"PRIx64"\n",
12568 				    un->un_pos.lgclblkno, value);
12569 			}
12570 			un->un_pos.lgclblkno = value;
12571 
12572 			if (long_pos_info->begin_of_part &&
12573 			    long_pos_info->end_of_part) {
12574 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
12575 				    "LONG_POS returned begin and end of"
12576 				    " partition\n");
12577 				break;
12578 			}
12579 			if ((long_pos_info->begin_of_part == 1) &&
12580 			    (long_pos_info->block_number == 0)) {
12581 				un->un_pos.blkno = 0;
12582 				un->un_pos.fileno = 0;
12583 				un->un_pos.pmode = legacy;
12584 			} else if (un->un_pos.pmode == invalid) {
12585 				un->un_pos.pmode = logical;
12586 			}
12587 		} else {
12588 			/*
12589 			 * If the drive doesn't know location,
12590 			 * we don't either.
12591 			 */
12592 			un->un_pos.pmode = invalid;
12593 		}
12594 
12595 		value = long_pos_info->file_number;
12596 		FIX_ENDIAN64(&value);
12597 		/* Is file position valid */
12598 		if (long_pos_info->mrk_posi_unkwn == 0) {
12599 			if (((un->un_pos.pmode == legacy) ||
12600 			    (un->un_pos.pmode == logical)) &&
12601 			    (un->un_pos.fileno != value)) {
12602 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
12603 				    "LONG_POS fileno 0x%"PRIx64
12604 				    " not un_pos %x\n", value,
12605 				    un->un_pos.fileno);
12606 			} else if (un->un_pos.pmode == invalid) {
12607 				un->un_pos.pmode = logical;
12608 			}
12609 			un->un_pos.fileno = (int32_t)value;
12610 		} else {
12611 			/*
12612 			 * If the drive doesn't know its position,
12613 			 * we don't either.
12614 			 */
12615 			un->un_pos.pmode = invalid;
12616 		}
12617 		if (un->un_pos.pmode != invalid && long_pos_info->end_of_part) {
12618 			un->un_pos.eof = ST_EOT;
12619 		}
12620 
12621 		break;
12622 	}
12623 
12624 	case EXT_POS: /* Extended data format */
12625 	{
12626 		uint64_t value;
12627 		tape_position_ext_t *ext_pos_info =
12628 		    (tape_position_ext_t *)responce;
12629 
12630 		/* Make sure that there is enough data there */
12631 		if (data_sz < 16) {
12632 			break;
12633 		}
12634 
12635 		/* If reserved fields are non zero don't use the data */
12636 		if (ext_pos_info->reserved0 || ext_pos_info->reserved1) {
12637 			rval = EIO;
12638 			break;
12639 		}
12640 
12641 		/*
12642 		 * In the unlikely event of overflowing 64 bits of position.
12643 		 */
12644 		if (ext_pos_info->posi_err != 0) {
12645 			rval = ERANGE;
12646 			break;
12647 		}
12648 
12649 		/* Is block position information valid */
12650 		if (ext_pos_info->blk_posi_unkwn == 0) {
12651 
12652 			if (un->un_pos.partition != ext_pos_info->partition) {
12653 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
12654 				    "EXT_POS current partition %d read %d\n",
12655 				    un->un_pos.partition,
12656 				    ext_pos_info->partition);
12657 			}
12658 			un->un_pos.partition = ext_pos_info->partition;
12659 
12660 			value = ext_pos_info->host_block;
12661 			FIX_ENDIAN64(&value);
12662 			if (un->un_pos.lgclblkno != value) {
12663 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
12664 				    "EXT_POS current logical 0x%"PRIx64
12665 				    " read 0x%"PRIx64"\n",
12666 				    un->un_pos.lgclblkno, value);
12667 			}
12668 			un->un_pos.lgclblkno = value;
12669 			if ((ext_pos_info->begin_of_part == 1) &&
12670 			    (ext_pos_info->host_block == 0)) {
12671 				un->un_pos.blkno = 0;
12672 				un->un_pos.fileno = 0;
12673 				un->un_pos.pmode = legacy;
12674 			} else if (un->un_pos.pmode == invalid) {
12675 				un->un_pos.pmode = logical;
12676 			}
12677 		} else {
12678 			un->un_pos.pmode = invalid;
12679 		}
12680 		break;
12681 	}
12682 
12683 	default:
12684 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
12685 		    "Got unexpected SCMD_READ_POSITION type %d\n", type);
12686 		rval = EIO;
12687 	}
12688 
12689 	return (rval);
12690 }
12691 
12692 static int
12693 st_logical_block_locate(struct scsi_tape *un, uint64_t lblk, uchar_t partition)
12694 {
12695 	int rval;
12696 	char cdb[CDB_GROUP4];
12697 	struct uscsi_cmd *cmd;
12698 	struct scsi_extended_sense sense;
12699 
12700 	ST_FUNC(ST_DEVINFO, st_logical_block_locate);
12701 
12702 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
12703 
12704 	if (lblk <= INT32_MAX) {
12705 		cmd->uscsi_cdblen = CDB_GROUP1;
12706 		cdb[0] = SCMD_LOCATE;
12707 		cdb[1] = un->un_pos.partition == partition ? 0 : 2;
12708 		cdb[2] = 0;
12709 		cdb[3] = (char)(lblk >> 24);
12710 		cdb[4] = (char)(lblk >> 16);
12711 		cdb[5] = (char)(lblk >> 8);
12712 		cdb[6] = (char)(lblk);
12713 		cdb[7] = 0;
12714 		cdb[8] = partition;
12715 		cdb[9] = 0;
12716 	} else {
12717 		/*
12718 		 * If the drive doesn't give a 64 bit read position data
12719 		 * it is unlikely it will accept 64 bit locates.
12720 		 */
12721 		if (un->un_read_pos_type != LONG_POS) {
12722 			kmem_free(cmd, sizeof (struct uscsi_cmd));
12723 			return (ERANGE);
12724 		}
12725 		cmd->uscsi_cdblen = CDB_GROUP4;
12726 		cdb[0] = (char)SCMD_LOCATE_G4;
12727 		cdb[1] = un->un_pos.partition == partition ? 0 : 2;
12728 		cdb[2] = 0;
12729 		cdb[3] = partition;
12730 		cdb[4] = (char)(lblk >> 56);
12731 		cdb[5] = (char)(lblk >> 48);
12732 		cdb[6] = (char)(lblk >> 40);
12733 		cdb[7] = (char)(lblk >> 32);
12734 		cdb[8] = (char)(lblk >> 24);
12735 		cdb[9] = (char)(lblk >> 16);
12736 		cdb[10] = (char)(lblk >> 8);
12737 		cdb[11] = (char)(lblk);
12738 		cdb[12] = 0;
12739 		cdb[13] = 0;
12740 		cdb[14] = 0;
12741 		cdb[15] = 0;
12742 	}
12743 
12744 
12745 	cmd->uscsi_flags = USCSI_WRITE | USCSI_DIAGNOSE | USCSI_RQENABLE;
12746 	cmd->uscsi_rqbuf = (caddr_t)&sense;
12747 	cmd->uscsi_rqlen = sizeof (sense);
12748 	cmd->uscsi_timeout = un->un_dp->space_timeout;
12749 	cmd->uscsi_cdb = cdb;
12750 
12751 	rval = st_ioctl_cmd(un->un_dev, cmd, FKIOCTL);
12752 
12753 	un->un_pos.pmode = logical;
12754 	un->un_pos.eof = ST_NO_EOF;
12755 
12756 	if (lblk > INT32_MAX) {
12757 		/*
12758 		 * XXX This is a work around till we handle Descriptor format
12759 		 * sense data. Since we are sending a command where the standard
12760 		 * sense data can not correctly represent a correct residual in
12761 		 * 4 bytes.
12762 		 */
12763 		if (un->un_status == KEY_ILLEGAL_REQUEST) {
12764 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
12765 			    "Big LOCATE ILLEGAL_REQUEST: rval = %d\n", rval);
12766 			/* Doesn't like big locate command */
12767 			un->un_status = 0;
12768 			rval = ERANGE;
12769 		} else if ((un->un_pos.pmode == invalid) || (rval != 0)) {
12770 			/* Aborted big locate command */
12771 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
12772 			    "Big LOCATE resulted in invalid pos: rval = %d\n",
12773 			    rval);
12774 			un->un_status = 0;
12775 			rval = EIO;
12776 		} else if (st_update_block_pos(un)) {
12777 			/* read position failed */
12778 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
12779 			    "Big LOCATE and read pos: rval = %d\n", rval);
12780 			rval = EIO;
12781 		} else if (lblk > un->un_pos.lgclblkno) {
12782 			/* read position worked but position was not expected */
12783 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
12784 			    "Big LOCATE and recover read less then desired 0x%"
12785 			    PRIx64"\n", un->un_pos.lgclblkno);
12786 			un->un_err_resid = lblk - un->un_pos.lgclblkno;
12787 			un->un_status = KEY_BLANK_CHECK;
12788 			rval = ESPIPE;
12789 		} else if (lblk == un->un_pos.lgclblkno) {
12790 			/* read position was what was expected */
12791 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
12792 			    "Big LOCATE and recover seems to have worked\n");
12793 			un->un_err_resid = 0;
12794 			rval = 0;
12795 		} else {
12796 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
12797 			    "BIGLOCATE end up going backwards");
12798 			un->un_err_resid = lblk;
12799 			rval = EIO;
12800 		}
12801 
12802 	} else if (rval == 0) {
12803 		/* Worked as requested */
12804 		un->un_pos.lgclblkno = lblk;
12805 
12806 	} else if (((cmd->uscsi_status & STATUS_MASK) == STATUS_CHECK) &&
12807 	    (cmd->uscsi_resid != 0)) {
12808 		/* Got part way there but wasn't enough blocks on tape */
12809 		un->un_pos.lgclblkno = lblk - cmd->uscsi_resid;
12810 		un->un_err_resid = cmd->uscsi_resid;
12811 		un->un_status = KEY_BLANK_CHECK;
12812 		rval = ESPIPE;
12813 
12814 	} else if (st_update_block_pos(un) == 0) {
12815 		/* Got part way there but drive didn't tell what we missed by */
12816 		un->un_err_resid = lblk - un->un_pos.lgclblkno;
12817 		un->un_status = KEY_BLANK_CHECK;
12818 		rval = ESPIPE;
12819 
12820 	} else {
12821 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
12822 		    "Failed LOCATE and recover pos: rval = %d status = %d\n",
12823 		    rval, cmd->uscsi_status);
12824 		un->un_err_resid = lblk;
12825 		un->un_status = KEY_ILLEGAL_REQUEST;
12826 		un->un_pos.pmode = invalid;
12827 		rval = EIO;
12828 	}
12829 
12830 	kmem_free(cmd, sizeof (struct uscsi_cmd));
12831 
12832 	return (rval);
12833 }
12834 
12835 static int
12836 st_mtfsf_ioctl(struct scsi_tape *un, int files)
12837 {
12838 	int rval;
12839 
12840 	ST_FUNC(ST_DEVINFO, st_mtfsf_ioctl);
12841 
12842 
12843 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
12844 	    "st_mtfsf_ioctl: count=%x, eof=%x\n", files, un->un_pos.eof);
12845 
12846 	/* pmode == invalid already handled */
12847 	if (un->un_pos.pmode == legacy) {
12848 		/*
12849 		 * forward space over filemark
12850 		 *
12851 		 * For ASF we allow a count of 0 on fsf which means
12852 		 * we just want to go to beginning of current file.
12853 		 * Equivalent to "nbsf(0)" or "bsf(1) + fsf".
12854 		 * Allow stepping over double fmk with reel
12855 		 */
12856 		if ((un->un_pos.eof >= ST_EOT) &&
12857 		    (files > 0) &&
12858 		    ((un->un_dp->options & ST_REEL) == 0)) {
12859 			/* we're at EOM */
12860 			un->un_err_resid = files;
12861 			un->un_status = KEY_BLANK_CHECK;
12862 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12863 			    "st_mtfsf_ioctl: EIO : MTFSF at EOM");
12864 			return (EIO);
12865 		}
12866 
12867 		/*
12868 		 * physical tape position may not be what we've been
12869 		 * telling the user; adjust the request accordingly
12870 		 */
12871 		if (IN_EOF(un->un_pos)) {
12872 			un->un_pos.fileno++;
12873 			un->un_pos.blkno = 0;
12874 			/*
12875 			 * For positive direction case, we're now covered.
12876 			 * For zero or negative direction, we're covered
12877 			 * (almost)
12878 			 */
12879 			files--;
12880 		}
12881 
12882 	}
12883 
12884 	if (st_check_density_or_wfm(un->un_dev, 1, B_READ, STEPBACK)) {
12885 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12886 		    "st_mtfsf_ioctl: EIO : MTFSF density/wfm failed");
12887 		return (EIO);
12888 	}
12889 
12890 
12891 	/*
12892 	 * Forward space file marks.
12893 	 * We leave ourselves at block zero
12894 	 * of the target file number.
12895 	 */
12896 	if (files < 0) {
12897 		rval = st_backward_space_files(un, -files, 0);
12898 	} else {
12899 		rval = st_forward_space_files(un, files);
12900 	}
12901 
12902 	return (rval);
12903 }
12904 
12905 static int
12906 st_forward_space_files(struct scsi_tape *un, int count)
12907 {
12908 	dev_t dev;
12909 	int rval;
12910 
12911 	ST_FUNC(ST_DEVINFO, st_forward_space_files);
12912 
12913 	dev = un->un_dev;
12914 
12915 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
12916 	    "fspace: count=%x, eof=%x\n", count, un->un_pos.eof);
12917 
12918 	ASSERT(count >= 0);
12919 	ASSERT(un->un_pos.pmode != invalid);
12920 
12921 	/*
12922 	 * A space with a count of zero means take me to the start of file.
12923 	 */
12924 	if (count == 0) {
12925 
12926 		/* Hay look were already there */
12927 		if (un->un_pos.pmode == legacy && un->un_pos.blkno == 0 &&
12928 		    un->un_pos.fileno == 0) {
12929 			un->un_err_resid = 0;
12930 			COPY_POS(&un->un_err_pos, &un->un_pos);
12931 			return (0);
12932 		}
12933 
12934 		/*
12935 		 * Well we are in the first file.
12936 		 * A rewind will get to the start.
12937 		 */
12938 		if (un->un_pos.pmode == legacy && un->un_pos.fileno == 0) {
12939 			rval = st_cmd(dev, SCMD_REWIND, 0, SYNC_CMD);
12940 
12941 		/*
12942 		 * Can we backspace to get there?
12943 		 * This should work in logical mode.
12944 		 */
12945 		} else if (un->un_dp->options & ST_BSF) {
12946 			rval = st_space_to_begining_of_file(un);
12947 
12948 		/*
12949 		 * Can't back space but current file number is known,
12950 		 * So rewind and space from the begining of the partition.
12951 		 */
12952 		} else if (un->un_pos.pmode == legacy) {
12953 			rval = st_scenic_route_to_begining_of_file(un,
12954 			    un->un_pos.fileno);
12955 
12956 		/*
12957 		 * pmode is logical and ST_BSF is not set.
12958 		 * The LONG_POS read position contains the fileno.
12959 		 * If the read position works, rewind and space.
12960 		 */
12961 		} else if (un->un_read_pos_type == LONG_POS) {
12962 			rval = st_cmd(dev, SCMD_READ_POSITION, 0, SYNC_CMD);
12963 			if (rval) {
12964 				/*
12965 				 * We didn't get the file position from the
12966 				 * read position command.
12967 				 * We are going to trust the drive to backspace
12968 				 * and then position after the filemark.
12969 				 */
12970 				rval = st_space_to_begining_of_file(un);
12971 			}
12972 			rval = st_interpret_read_pos(un, LONG_POS, 32,
12973 			    (caddr_t)un->un_read_pos_data);
12974 			if ((rval) && (un->un_pos.pmode == invalid)) {
12975 				rval = st_space_to_begining_of_file(un);
12976 			} else {
12977 				rval = st_scenic_route_to_begining_of_file(un,
12978 				    un->un_pos.fileno);
12979 			}
12980 		} else {
12981 			rval = EIO;
12982 		}
12983 		/*
12984 		 * If something didn't work we are lost
12985 		 */
12986 		if (rval != 0) {
12987 			un->un_pos.pmode = invalid;
12988 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12989 			    "st_mtioctop : EIO : fspace pmode invalid");
12990 
12991 			rval = EIO;
12992 		}
12993 
12994 	} else {
12995 		rval = st_space_fmks(dev, count);
12996 	}
12997 
12998 	if (rval != EIO && count < 0) {
12999 		/*
13000 		 * we came here with a count < 0; we now need
13001 		 * to skip back to end up before the filemark
13002 		 */
13003 		rval = st_backward_space_files(un, 1, 1);
13004 	}
13005 
13006 	return (rval);
13007 }
13008 
13009 static int
13010 st_scenic_route_to_begining_of_file(struct scsi_tape *un, int32_t fileno)
13011 {
13012 	int rval;
13013 
13014 	ST_FUNC(ST_DEVINFO, st_scenic_route_to_begining_of_file);
13015 
13016 	if (st_cmd(un->un_dev, SCMD_REWIND, 0, SYNC_CMD)) {
13017 		rval = EIO;
13018 	} else if (st_cmd(un->un_dev, SCMD_SPACE, Fmk(fileno), SYNC_CMD)) {
13019 		rval = EIO;
13020 	}
13021 
13022 	return (rval);
13023 }
13024 
13025 static int
13026 st_space_to_begining_of_file(struct scsi_tape *un)
13027 {
13028 	int rval;
13029 
13030 	ST_FUNC(ST_DEVINFO, st_space_to_begining_of_file);
13031 
13032 	/*
13033 	 * Back space of the file at the begining of the file.
13034 	 */
13035 	rval = st_cmd(un->un_dev, SCMD_SPACE, Fmk((-1)), SYNC_CMD);
13036 	if (rval) {
13037 		rval = EIO;
13038 		return (rval);
13039 	}
13040 
13041 	/*
13042 	 * Other interesting answers might be crashed BOT which isn't bad.
13043 	 */
13044 	if (un->un_status == SUN_KEY_BOT) {
13045 		return (rval);
13046 	}
13047 
13048 	/*
13049 	 * Now we are on the BOP side of the filemark. Forward space to
13050 	 * the EOM side and we are at the begining of the file.
13051 	 */
13052 	rval = st_cmd(un->un_dev, SCMD_SPACE, Fmk(1), SYNC_CMD);
13053 	if (rval) {
13054 		rval = EIO;
13055 	}
13056 
13057 	return (rval);
13058 }
13059 
13060 static int
13061 st_mtfsr_ioctl(struct scsi_tape *un, int count)
13062 {
13063 
13064 	ST_FUNC(ST_DEVINFO, st_mtfsr_ioctl);
13065 
13066 	/*
13067 	 * forward space to inter-record gap
13068 	 *
13069 	 */
13070 
13071 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13072 	    "st_ioctl_fsr: count=%x, eof=%x\n", count, un->un_pos.eof);
13073 
13074 	if (un->un_pos.pmode == legacy) {
13075 		/*
13076 		 * If were are at end of tape and count is forward.
13077 		 * Return blank check.
13078 		 */
13079 		if ((un->un_pos.eof >= ST_EOT) && (count > 0)) {
13080 			/* we're at EOM */
13081 			un->un_err_resid = count;
13082 			un->un_status = KEY_BLANK_CHECK;
13083 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13084 			    "st_mtfsr_ioctl: EIO : MTFSR eof > ST_EOT");
13085 			return (EIO);
13086 		}
13087 
13088 		/*
13089 		 * If count is zero there is nothing to do.
13090 		 */
13091 		if (count == 0) {
13092 			un->un_err_pos.fileno = un->un_pos.fileno;
13093 			un->un_err_pos.blkno = un->un_pos.blkno;
13094 			un->un_err_resid = 0;
13095 			if (IN_EOF(un->un_pos) && SVR4_BEHAVIOR) {
13096 				un->un_status = SUN_KEY_EOF;
13097 			}
13098 			return (0);
13099 		}
13100 
13101 		/*
13102 		 * physical tape position may not be what we've been
13103 		 * telling the user; adjust the position accordingly
13104 		 */
13105 		if (IN_EOF(un->un_pos)) {
13106 			daddr_t blkno = un->un_pos.blkno;
13107 			int fileno = un->un_pos.fileno;
13108 
13109 			optype lastop = un->un_lastop;
13110 			if (st_cmd(un->un_dev, SCMD_SPACE, Fmk((-1)), SYNC_CMD)
13111 			    == -1) {
13112 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13113 				    "st_mtfsr_ioctl:EIO:MTFSR count && IN_EOF");
13114 				return (EIO);
13115 			}
13116 
13117 			un->un_pos.blkno = blkno;
13118 			un->un_pos.fileno = fileno;
13119 			un->un_lastop = lastop;
13120 		}
13121 	}
13122 
13123 	if (st_check_density_or_wfm(un->un_dev, 1, B_READ, STEPBACK)) {
13124 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13125 		    "st_mtfsr_ioctl: EIO : MTFSR st_check_den");
13126 		return (EIO);
13127 	}
13128 
13129 	return (st_space_records(un, count));
13130 }
13131 
13132 static int
13133 st_space_records(struct scsi_tape *un, int count)
13134 {
13135 	int dblk;
13136 	int rval = 0;
13137 
13138 	ST_FUNC(ST_DEVINFO, st_space_records);
13139 
13140 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13141 	    "st_space_records: count=%x, eof=%x\n", count, un->un_pos.eof);
13142 
13143 	if (un->un_pos.pmode == logical) {
13144 		rval = st_cmd(un->un_dev, SCMD_SPACE, Blk(count), SYNC_CMD);
13145 		if (rval != 0) {
13146 			rval = EIO;
13147 		}
13148 		return (rval);
13149 	}
13150 
13151 	dblk = un->un_pos.blkno + count;
13152 
13153 	/* Already there */
13154 	if (dblk == un->un_pos.blkno) {
13155 		un->un_err_resid = 0;
13156 		COPY_POS(&un->un_err_pos, &un->un_pos);
13157 		return (0);
13158 	}
13159 
13160 	/*
13161 	 * If the destination block is forward
13162 	 * or the drive will backspace records.
13163 	 */
13164 	if (un->un_pos.blkno < dblk || (un->un_dp->options & ST_BSR)) {
13165 		/*
13166 		 * If we're spacing forward, or the device can
13167 		 * backspace records, we can just use the SPACE
13168 		 * command.
13169 		 */
13170 		dblk -= un->un_pos.blkno;
13171 		if (st_cmd(un->un_dev, SCMD_SPACE, Blk(dblk), SYNC_CMD)) {
13172 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13173 			    "st_space_records:EIO:space_records can't spc");
13174 			rval = EIO;
13175 		} else if (un->un_pos.eof >= ST_EOF_PENDING) {
13176 			/*
13177 			 * check if we hit BOT/EOT
13178 			 */
13179 			if (dblk < 0 && un->un_pos.eof == ST_EOM) {
13180 				un->un_status = SUN_KEY_BOT;
13181 				un->un_pos.eof = ST_NO_EOF;
13182 			} else if (dblk < 0 &&
13183 			    un->un_pos.eof == ST_EOF_PENDING) {
13184 				int residue = un->un_err_resid;
13185 				/*
13186 				 * we skipped over a filemark
13187 				 * and need to go forward again
13188 				 */
13189 				if (st_cmd(un->un_dev, SCMD_SPACE, Fmk(1),
13190 				    SYNC_CMD)) {
13191 					ST_DEBUG2(ST_DEVINFO, st_label,
13192 					    SCSI_DEBUG, "st_space_records: EIO"
13193 					    " : can't space #2");
13194 					rval = EIO;
13195 				}
13196 				un->un_err_resid = residue;
13197 			}
13198 			if (rval == 0) {
13199 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13200 				    "st_space_records: EIO : space_rec rval"
13201 				    " == 0");
13202 				rval = EIO;
13203 			}
13204 		}
13205 	} else {
13206 		/*
13207 		 * else we rewind, space forward across filemarks to
13208 		 * the desired file, and then space records to the
13209 		 * desired block.
13210 		 */
13211 
13212 		int dfile = un->un_pos.fileno;	/* save current file */
13213 
13214 		if (dblk < 0) {
13215 			/*
13216 			 * Wups - we're backing up over a filemark
13217 			 */
13218 			if (un->un_pos.blkno != 0 &&
13219 			    (st_cmd(un->un_dev, SCMD_REWIND, 0, SYNC_CMD) ||
13220 			    st_cmd(un->un_dev, SCMD_SPACE, Fmk(dfile),
13221 			    SYNC_CMD))) {
13222 				un->un_pos.pmode = invalid;
13223 			}
13224 			un->un_err_resid = -dblk;
13225 			if (un->un_pos.fileno == 0 && un->un_pos.blkno == 0) {
13226 				un->un_status = SUN_KEY_BOT;
13227 				un->un_pos.eof = ST_NO_EOF;
13228 			} else if (un->un_pos.fileno > 0) {
13229 				un->un_status = SUN_KEY_EOF;
13230 				un->un_pos.eof = ST_NO_EOF;
13231 			}
13232 			COPY_POS(&un->un_err_pos, &un->un_pos);
13233 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13234 			    "st_space_records:EIO:space_records : dblk < 0");
13235 			rval = EIO;
13236 		} else if (st_cmd(un->un_dev, SCMD_REWIND, 0, SYNC_CMD) ||
13237 		    st_cmd(un->un_dev, SCMD_SPACE, Fmk(dfile), SYNC_CMD) ||
13238 		    st_cmd(un->un_dev, SCMD_SPACE, Blk(dblk), SYNC_CMD)) {
13239 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13240 			    "st_space_records: EIO :space_records : rewind "
13241 			    "and space failed");
13242 			un->un_pos.pmode = invalid;
13243 			rval = EIO;
13244 		}
13245 	}
13246 
13247 	return (rval);
13248 }
13249 
13250 static int
13251 st_mtbsf_ioctl(struct scsi_tape *un, int files)
13252 {
13253 	ST_FUNC(ST_DEVINFO, st_mtbsf_ioctl);
13254 
13255 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13256 	    "st_mtbsf_ioctl: count=%x, eof=%x\n", files, un->un_pos.eof);
13257 	/*
13258 	 * backward space of file filemark (1/2" and 8mm)
13259 	 * tape position will end on the beginning of tape side
13260 	 * of the desired file mark
13261 	 */
13262 	if ((un->un_dp->options & ST_BSF) == 0) {
13263 		return (ENOTTY);
13264 	}
13265 
13266 	if (un->un_pos.pmode == legacy) {
13267 
13268 		/*
13269 		 * If a negative count (which implies a forward space op)
13270 		 * is specified, and we're at logical or physical eot,
13271 		 * bounce the request.
13272 		 */
13273 
13274 		if (un->un_pos.eof >= ST_EOT && files < 0) {
13275 			un->un_err_resid = files;
13276 			un->un_status = SUN_KEY_EOT;
13277 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13278 			    "st_ioctl_mt_bsf : EIO : MTBSF : eof > ST_EOF");
13279 			return (EIO);
13280 		}
13281 		/*
13282 		 * physical tape position may not be what we've been
13283 		 * telling the user; adjust the request accordingly
13284 		 */
13285 		if (IN_EOF(un->un_pos)) {
13286 			un->un_pos.fileno++;
13287 			un->un_pos.blkno = 0;
13288 			files++;
13289 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13290 			    "st_mtbsf_ioctl in eof: count=%d, op=%x\n",
13291 			    files, MTBSF);
13292 
13293 		}
13294 	}
13295 
13296 	if (st_check_density_or_wfm(un->un_dev, 1, 0, STEPBACK)) {
13297 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13298 		    "st_ioctl : EIO : MTBSF : check den wfm");
13299 		return (EIO);
13300 	}
13301 
13302 	if (files <= 0) {
13303 		/*
13304 		 * for a negative count, we need to step forward
13305 		 * first and then step back again
13306 		 */
13307 		files = -files + 1;
13308 		return (st_forward_space_files(un, files));
13309 	}
13310 	return (st_backward_space_files(un, files, 1));
13311 }
13312 
13313 static int
13314 st_backward_space_files(struct scsi_tape *un, int count, int infront)
13315 {
13316 	int end_fileno;
13317 	int skip_cnt;
13318 	int rval = 0;
13319 
13320 	ST_FUNC(ST_DEVINFO, st_backward_space_files);
13321 
13322 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13323 	    "st_backward_space_files: count=%x eof=%x\n",
13324 	    count, un->un_pos.eof);
13325 	/*
13326 	 * Backspace files (MTNBSF): infront == 0
13327 	 *
13328 	 *	For tapes that can backspace, backspace
13329 	 *	count+1 filemarks and then run forward over
13330 	 *	a filemark
13331 	 *
13332 	 *	For tapes that can't backspace,
13333 	 *		calculate desired filenumber
13334 	 *		(un->un_pos.fileno - count), rewind,
13335 	 *		and then space forward this amount
13336 	 *
13337 	 * Backspace filemarks (MTBSF) infront == 1
13338 	 *
13339 	 *	For tapes that can backspace, backspace count
13340 	 *	filemarks
13341 	 *
13342 	 *	For tapes that can't backspace, calculate
13343 	 *	desired filenumber (un->un_pos.fileno - count),
13344 	 *	add 1, rewind, space forward this amount,
13345 	 *	and mark state as ST_EOF_PENDING appropriately.
13346 	 */
13347 
13348 	if (un->un_pos.pmode == logical) {
13349 
13350 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13351 		    "st_backward_space_files: mt_op=%x count=%x"
13352 		    "lgclblkno=%"PRIx64"\n", infront?MTBSF:MTNBSF, count,
13353 		    un->un_pos.lgclblkno);
13354 
13355 
13356 		/* In case a drive that won't back space gets in logical mode */
13357 		if ((un->un_dp->options & ST_BSF) == 0) {
13358 			rval = EIO;
13359 			return (rval);
13360 		}
13361 		if (st_cmd(un->un_dev, SCMD_SPACE, Fmk(-count), SYNC_CMD)) {
13362 			rval = EIO;
13363 			return (rval);
13364 		}
13365 		if ((infront != 0) &&
13366 		    (st_cmd(un->un_dev, SCMD_SPACE, Fmk(1), SYNC_CMD))) {
13367 			rval = EIO;
13368 			return (rval);
13369 		}
13370 		return (rval);
13371 	}
13372 
13373 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13374 	    "st_backward_space_files: mt_op=%x count=%x fileno=%x blkno=%x\n",
13375 	    infront?MTBSF:MTNBSF, count, un->un_pos.fileno, un->un_pos.blkno);
13376 
13377 
13378 
13379 	/*
13380 	 * Handle the simple case of BOT
13381 	 * playing a role in these cmds.
13382 	 * We do this by calculating the
13383 	 * ending file number. If the ending
13384 	 * file is < BOT, rewind and set an
13385 	 * error and mark resid appropriately.
13386 	 * If we're backspacing a file (not a
13387 	 * filemark) and the target file is
13388 	 * the first file on the tape, just
13389 	 * rewind.
13390 	 */
13391 
13392 	/* figure expected destination of this SPACE command */
13393 	end_fileno = un->un_pos.fileno - count;
13394 
13395 	/*
13396 	 * Would the end effect of this SPACE be the same as rewinding?
13397 	 * If so just rewind instead.
13398 	 */
13399 	if ((infront != 0) && (end_fileno < 0) ||
13400 	    (infront == 0) && (end_fileno <= 0)) {
13401 		if (st_cmd(un->un_dev, SCMD_REWIND, 0, SYNC_CMD)) {
13402 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13403 			    "st_backward_space_files: EIO : "
13404 			    "rewind in lou of BSF failed\n");
13405 			rval = EIO;
13406 		}
13407 		if (end_fileno < 0) {
13408 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13409 			    "st_backward_space_files: EIO : "
13410 			    "back space file greater then fileno\n");
13411 			rval = EIO;
13412 			un->un_err_resid = -end_fileno;
13413 			un->un_status = SUN_KEY_BOT;
13414 		}
13415 		return (rval);
13416 	}
13417 
13418 	if (un->un_dp->options & ST_BSF) {
13419 		skip_cnt = 1 - infront;
13420 		/*
13421 		 * If we are going to end up at the beginning
13422 		 * of the file, we have to space one extra file
13423 		 * first, and then space forward later.
13424 		 */
13425 		end_fileno = -(count + skip_cnt);
13426 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
13427 		    "skip_cnt=%x, tmp=%x\n", skip_cnt, end_fileno);
13428 		if (st_cmd(un->un_dev, SCMD_SPACE, Fmk(end_fileno), SYNC_CMD)) {
13429 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13430 			    "st_backward_space_files:EIO:back space fm failed");
13431 			rval = EIO;
13432 		}
13433 	} else {
13434 		if (st_cmd(un->un_dev, SCMD_REWIND, 0, SYNC_CMD)) {
13435 			rval = EIO;
13436 		} else {
13437 			skip_cnt = end_fileno + infront;
13438 		}
13439 	}
13440 
13441 	/*
13442 	 * If we have to space forward, do so...
13443 	 */
13444 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
13445 	    "space forward skip_cnt=%x, rval=%x\n", skip_cnt, rval);
13446 
13447 	if (rval == 0 && skip_cnt) {
13448 		if (st_cmd(un->un_dev, SCMD_SPACE, Fmk(skip_cnt), SYNC_CMD)) {
13449 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13450 			    "st_backward_space_files:EIO:space fm skip count");
13451 			rval = EIO;
13452 		} else if (infront) {
13453 			/*
13454 			 * If we had to space forward, and we're
13455 			 * not a tape that can backspace, mark state
13456 			 * as if we'd just seen a filemark during a
13457 			 * a read.
13458 			 */
13459 			if ((un->un_dp->options & ST_BSF) == 0) {
13460 				un->un_pos.eof = ST_EOF_PENDING;
13461 				un->un_pos.fileno -= 1;
13462 				un->un_pos.blkno = INF;
13463 			}
13464 		}
13465 	}
13466 
13467 	if (rval != 0) {
13468 		un->un_pos.pmode = invalid;
13469 	}
13470 
13471 	return (rval);
13472 }
13473 
13474 static int
13475 st_mtnbsf_ioctl(struct scsi_tape *un, int count)
13476 {
13477 	int rval;
13478 
13479 	ST_FUNC(ST_DEVINFO, st_mtnbsf_ioctl);
13480 
13481 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13482 	    "nbsf: count=%x, eof=%x\n", count, un->un_pos.eof);
13483 
13484 	if (un->un_pos.pmode == legacy) {
13485 		/*
13486 		 * backward space file to beginning of file
13487 		 *
13488 		 * If a negative count (which implies a forward space op)
13489 		 * is specified, and we're at logical or physical eot,
13490 		 * bounce the request.
13491 		 */
13492 
13493 		if (un->un_pos.eof >= ST_EOT && count < 0) {
13494 			un->un_err_resid = count;
13495 			un->un_status = SUN_KEY_EOT;
13496 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13497 			    "st_ioctl : EIO : > EOT and count < 0");
13498 			return (EIO);
13499 		}
13500 		/*
13501 		 * physical tape position may not be what we've been
13502 		 * telling the user; adjust the request accordingly
13503 		 */
13504 		if (IN_EOF(un->un_pos)) {
13505 			un->un_pos.fileno++;
13506 			un->un_pos.blkno = 0;
13507 			count++;
13508 		}
13509 	}
13510 
13511 	if (st_check_density_or_wfm(un->un_dev, 1, 0, STEPBACK)) {
13512 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13513 		    "st_ioctl : EIO : MTNBSF check den and wfm");
13514 		return (EIO);
13515 	}
13516 
13517 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13518 	    "mtnbsf: count=%x, eof=%x\n", count, un->un_pos.eof);
13519 
13520 	if (count <= 0) {
13521 		rval = st_forward_space_files(un, -count);
13522 	} else {
13523 		rval = st_backward_space_files(un, count, 0);
13524 	}
13525 	return (rval);
13526 }
13527 
13528 static int
13529 st_mtbsr_ioctl(struct scsi_tape *un, int num)
13530 {
13531 	ST_FUNC(ST_DEVINFO, st_mtbsr_ioctl);
13532 
13533 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13534 	    "bsr: count=%x, eof=%x\n", num, un->un_pos.eof);
13535 
13536 	if (un->un_pos.pmode == legacy) {
13537 		/*
13538 		 * backward space into inter-record gap
13539 		 *
13540 		 * If a negative count (which implies a forward space op)
13541 		 * is specified, and we're at logical or physical eot,
13542 		 * bounce the request.
13543 		 */
13544 		if (un->un_pos.eof >= ST_EOT && num < 0) {
13545 			un->un_err_resid = num;
13546 			un->un_status = SUN_KEY_EOT;
13547 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13548 			    "st_ioctl : EIO : MTBSR > EOT");
13549 			return (EIO);
13550 		}
13551 
13552 		if (num == 0) {
13553 			COPY_POS(&un->un_err_pos, &un->un_pos);
13554 			un->un_err_resid = 0;
13555 			if (IN_EOF(un->un_pos) && SVR4_BEHAVIOR) {
13556 				un->un_status = SUN_KEY_EOF;
13557 			}
13558 			return (0);
13559 		}
13560 
13561 		/*
13562 		 * physical tape position may not be what we've been
13563 		 * telling the user; adjust the position accordingly.
13564 		 * bsr can not skip filemarks and continue to skip records
13565 		 * therefore if we are logically before the filemark but
13566 		 * physically at the EOT side of the filemark, we need to step
13567 		 * back; this allows fsr N where N > number of blocks in file
13568 		 * followed by bsr 1 to position at the beginning of last block
13569 		 */
13570 		if (IN_EOF(un->un_pos)) {
13571 			tapepos_t save;
13572 			optype lastop = un->un_lastop;
13573 
13574 			COPY_POS(&save, &un->un_pos);
13575 			if (st_cmd(un->un_dev, SCMD_SPACE, Fmk((-1)), SYNC_CMD)
13576 			    == -1) {
13577 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13578 				    "st_write_fm : EIO : MTBSR can't space");
13579 				return (EIO);
13580 			}
13581 
13582 			COPY_POS(&un->un_pos, &save);
13583 			un->un_lastop = lastop;
13584 		}
13585 	}
13586 
13587 	un->un_pos.eof = ST_NO_EOF;
13588 
13589 	if (st_check_density_or_wfm(un->un_dev, 1, 0, STEPBACK)) {
13590 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13591 		    "st_ioctl : EIO : MTBSR : can't set density or wfm");
13592 		return (EIO);
13593 	}
13594 
13595 	num = -num;
13596 	return (st_space_records(un, num));
13597 }
13598 
13599 static int
13600 st_mtfsfm_ioctl(struct scsi_tape *un, int cnt)
13601 {
13602 	int rval;
13603 
13604 	ST_FUNC(ST_DEVINFO, st_mtfsfm_ioctl);
13605 
13606 	rval = st_cmd(un->un_dev, SCMD_SPACE, SPACE(SP_SQFLM, cnt), SYNC_CMD);
13607 	if (rval == 0) {
13608 		un->un_pos.pmode = logical;
13609 	} else if ((un->un_status == KEY_ILLEGAL_REQUEST) &&
13610 	    (un->un_sd->sd_sense->es_add_code == 0x24)) {
13611 		/*
13612 		 * Drive says invalid field in cdb.
13613 		 * Doesn't like space multiple. Position isn't lost.
13614 		 */
13615 		un->un_err_resid = cnt;
13616 		un->un_status = 0;
13617 		rval = ENOTTY;
13618 	} else {
13619 		un->un_err_resid = cnt;
13620 		un->un_pos.pmode = invalid;
13621 	}
13622 	return (rval);
13623 }
13624 
13625 static int
13626 st_mtbsfm_ioctl(struct scsi_tape *un, int cnt)
13627 {
13628 	int rval;
13629 
13630 	ST_FUNC(ST_DEVINFO, st_mtbsfm_ioctl);
13631 
13632 	rval = st_cmd(un->un_dev, SCMD_SPACE, SPACE(SP_SQFLM, -cnt), SYNC_CMD);
13633 	if (rval == 0) {
13634 		un->un_pos.pmode = logical;
13635 	} else if ((un->un_status == KEY_ILLEGAL_REQUEST) &&
13636 	    (un->un_sd->sd_sense->es_add_code == 0x24)) {
13637 		/*
13638 		 * Drive says invalid field in cdb.
13639 		 * Doesn't like space multiple. Position isn't lost.
13640 		 */
13641 		un->un_err_resid = cnt;
13642 		un->un_status = 0;
13643 		rval = ENOTTY;
13644 	} else {
13645 		un->un_err_resid = cnt;
13646 		un->un_pos.pmode = invalid;
13647 	}
13648 	return (rval);
13649 }
13650 
13651 #if defined(__i386) || defined(__amd64)
13652 
13653 /*
13654  * release contig_mem and wake up waiting thread, if any
13655  */
13656 static void
13657 st_release_contig_mem(struct scsi_tape *un, struct contig_mem *cp)
13658 {
13659 	mutex_enter(ST_MUTEX);
13660 
13661 	ST_FUNC(ST_DEVINFO, st_release_contig_mem);
13662 
13663 	cp->cm_next = un->un_contig_mem;
13664 	un->un_contig_mem = cp;
13665 	un->un_contig_mem_available_num++;
13666 	cv_broadcast(&un->un_contig_mem_cv);
13667 
13668 	mutex_exit(ST_MUTEX);
13669 }
13670 
13671 /*
13672  * St_get_contig_mem will return a contig_mem if there is one available
13673  * in current system. Otherwise, it will try to alloc one, if the total
13674  * number of contig_mem is within st_max_contig_mem_num.
13675  * It will sleep, if allowed by caller or return NULL, if no contig_mem
13676  * is available for now.
13677  */
13678 static struct contig_mem *
13679 st_get_contig_mem(struct scsi_tape *un, size_t len, int alloc_flags)
13680 {
13681 	size_t rlen;
13682 	struct contig_mem *cp = NULL;
13683 	ddi_acc_handle_t acc_hdl;
13684 	caddr_t addr;
13685 	int big_enough = 0;
13686 	int (*dma_alloc_cb)() = (alloc_flags == KM_SLEEP) ?
13687 	    DDI_DMA_SLEEP : DDI_DMA_DONTWAIT;
13688 
13689 	/* Try to get one available contig_mem */
13690 	mutex_enter(ST_MUTEX);
13691 
13692 	ST_FUNC(ST_DEVINFO, st_get_contig_mem);
13693 
13694 	if (un->un_contig_mem_available_num > 0) {
13695 		ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough);
13696 	} else if (un->un_contig_mem_total_num < st_max_contig_mem_num) {
13697 		/*
13698 		 * we failed to get one. we're going to
13699 		 * alloc one more contig_mem for this I/O
13700 		 */
13701 		mutex_exit(ST_MUTEX);
13702 		cp = (struct contig_mem *)kmem_zalloc(
13703 		    sizeof (struct contig_mem) + biosize(),
13704 		    alloc_flags);
13705 		if (cp == NULL) {
13706 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13707 			    "alloc contig_mem failure\n");
13708 			return (NULL); /* cannot get one */
13709 		}
13710 		cp->cm_bp = (struct buf *)
13711 		    (((caddr_t)cp) + sizeof (struct contig_mem));
13712 		bioinit(cp->cm_bp);
13713 		mutex_enter(ST_MUTEX);
13714 		un->un_contig_mem_total_num++; /* one more available */
13715 	} else {
13716 		/*
13717 		 * we failed to get one and we're NOT allowed to
13718 		 * alloc more contig_mem
13719 		 */
13720 		if (alloc_flags == KM_SLEEP) {
13721 			while (un->un_contig_mem_available_num <= 0) {
13722 				cv_wait(&un->un_contig_mem_cv,
13723 				    ST_MUTEX);
13724 			}
13725 			ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough);
13726 		} else {
13727 			mutex_exit(ST_MUTEX);
13728 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13729 			    "alloc contig_mem failure\n");
13730 			return (NULL); /* cannot get one */
13731 		}
13732 	}
13733 	mutex_exit(ST_MUTEX);
13734 
13735 	/* We need to check if this block of mem is big enough for this I/O */
13736 	if (cp->cm_len < len) {
13737 		/* not big enough, need to alloc a new one */
13738 		if (ddi_dma_mem_alloc(un->un_contig_mem_hdl, len, &st_acc_attr,
13739 		    DDI_DMA_STREAMING, dma_alloc_cb, NULL,
13740 		    &addr, &rlen, &acc_hdl) != DDI_SUCCESS) {
13741 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13742 			    "alloc contig_mem failure: not enough mem\n");
13743 			st_release_contig_mem(un, cp);
13744 			cp = NULL;
13745 		} else {
13746 			if (cp->cm_addr) {
13747 				/* release previous one before attach new one */
13748 				ddi_dma_mem_free(&cp->cm_acc_hdl);
13749 			}
13750 			mutex_enter(ST_MUTEX);
13751 			un->un_max_contig_mem_len =
13752 			    un->un_max_contig_mem_len >= len ?
13753 			    un->un_max_contig_mem_len : len;
13754 			mutex_exit(ST_MUTEX);
13755 
13756 			/* attach new mem to this cp */
13757 			cp->cm_addr = addr;
13758 			cp->cm_acc_hdl = acc_hdl;
13759 			cp->cm_len = len;
13760 
13761 			goto alloc_ok; /* get one usable cp */
13762 		}
13763 	} else {
13764 		goto alloc_ok; /* get one usable cp */
13765 	}
13766 
13767 	/* cannot find/alloc a usable cp, when we get here */
13768 
13769 	mutex_enter(ST_MUTEX);
13770 	if ((un->un_max_contig_mem_len < len) ||
13771 	    (alloc_flags != KM_SLEEP)) {
13772 		mutex_exit(ST_MUTEX);
13773 		return (NULL);
13774 	}
13775 
13776 	/*
13777 	 * we're allowed to sleep, and there is one big enough
13778 	 * contig mem in the system, which is currently in use,
13779 	 * wait for it...
13780 	 */
13781 	big_enough = 1;
13782 	do {
13783 		cv_wait(&un->un_contig_mem_cv, ST_MUTEX);
13784 		ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough);
13785 	} while (cp == NULL);
13786 	mutex_exit(ST_MUTEX);
13787 
13788 	/* we get the big enough contig mem, finally */
13789 
13790 alloc_ok:
13791 	/* init bp attached to this cp */
13792 	bioreset(cp->cm_bp);
13793 	cp->cm_bp->b_un.b_addr = cp->cm_addr;
13794 	cp->cm_bp->b_private = (void *)cp;
13795 
13796 	return (cp);
13797 }
13798 
13799 /*
13800  * this is the biodone func for the bp used in big block I/O
13801  */
13802 static int
13803 st_bigblk_xfer_done(struct buf *bp)
13804 {
13805 	struct contig_mem *cp;
13806 	struct buf *orig_bp;
13807 	int remapped = 0;
13808 	int ioerr;
13809 	struct scsi_tape *un;
13810 
13811 	/* sanity check */
13812 	if (bp == NULL) {
13813 		return (DDI_FAILURE);
13814 	}
13815 
13816 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
13817 	if (un == NULL) {
13818 		return (DDI_FAILURE);
13819 	}
13820 
13821 	ST_FUNC(ST_DEVINFO, st_bigblk_xfer_done);
13822 
13823 	cp = (struct contig_mem *)bp->b_private;
13824 	orig_bp = cp->cm_bp; /* get back the bp we have replaced */
13825 	cp->cm_bp = bp;
13826 
13827 	/* special handling for special I/O */
13828 	if (cp->cm_use_sbuf) {
13829 #ifndef __lock_lint
13830 		ASSERT(un->un_sbuf_busy);
13831 #endif
13832 		un->un_sbufp = orig_bp;
13833 		cp->cm_use_sbuf = 0;
13834 	}
13835 
13836 	orig_bp->b_resid = bp->b_resid;
13837 	ioerr = geterror(bp);
13838 	if (ioerr != 0) {
13839 		bioerror(orig_bp, ioerr);
13840 	} else if (orig_bp->b_flags & B_READ) {
13841 		/* copy data back to original bp */
13842 		if (orig_bp->b_flags & (B_PHYS | B_PAGEIO)) {
13843 			bp_mapin(orig_bp);
13844 			remapped = 1;
13845 		}
13846 		bcopy(bp->b_un.b_addr, orig_bp->b_un.b_addr,
13847 		    bp->b_bcount - bp->b_resid);
13848 		if (remapped)
13849 			bp_mapout(orig_bp);
13850 	}
13851 
13852 	st_release_contig_mem(un, cp);
13853 
13854 	biodone(orig_bp);
13855 
13856 	return (DDI_SUCCESS);
13857 }
13858 
13859 /*
13860  * We use this func to replace original bp that may not be able to do I/O
13861  * in big block size with one that can
13862  */
13863 static struct buf *
13864 st_get_bigblk_bp(struct buf *bp)
13865 {
13866 	struct contig_mem *cp;
13867 	struct scsi_tape *un;
13868 	struct buf *cont_bp;
13869 	int remapped = 0;
13870 
13871 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
13872 	if (un == NULL) {
13873 		return (bp);
13874 	}
13875 
13876 	ST_FUNC(ST_DEVINFO, st_get_bigblk_bp);
13877 
13878 	/* try to get one contig_mem */
13879 	cp = st_get_contig_mem(un, bp->b_bcount, KM_SLEEP);
13880 	if (!cp) {
13881 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
13882 		    "Cannot alloc contig buf for I/O for %lu blk size",
13883 		    bp->b_bcount);
13884 		return (bp);
13885 	}
13886 	cont_bp = cp->cm_bp;
13887 	cp->cm_bp = bp;
13888 
13889 	/* make sure that we "are" using un_sbufp for special I/O */
13890 	if (bp == un->un_sbufp) {
13891 #ifndef __lock_lint
13892 		ASSERT(un->un_sbuf_busy);
13893 #endif
13894 		un->un_sbufp = cont_bp;
13895 		cp->cm_use_sbuf = 1;
13896 	}
13897 
13898 	/* clone bp */
13899 	cont_bp->b_bcount = bp->b_bcount;
13900 	cont_bp->b_resid = bp->b_resid;
13901 	cont_bp->b_iodone = st_bigblk_xfer_done;
13902 	cont_bp->b_file = bp->b_file;
13903 	cont_bp->b_offset = bp->b_offset;
13904 	cont_bp->b_dip = bp->b_dip;
13905 	cont_bp->b_error = 0;
13906 	cont_bp->b_proc = NULL;
13907 	cont_bp->b_flags = bp->b_flags & ~(B_PAGEIO | B_PHYS | B_SHADOW);
13908 	cont_bp->b_shadow = NULL;
13909 	cont_bp->b_pages = NULL;
13910 	cont_bp->b_edev = bp->b_edev;
13911 	cont_bp->b_dev = bp->b_dev;
13912 	cont_bp->b_lblkno = bp->b_lblkno;
13913 	cont_bp->b_forw = bp->b_forw;
13914 	cont_bp->b_back = bp->b_back;
13915 	cont_bp->av_forw = bp->av_forw;
13916 	cont_bp->av_back = bp->av_back;
13917 	cont_bp->b_bufsize = bp->b_bufsize;
13918 
13919 	/* get data in original bp */
13920 	if (bp->b_flags & B_WRITE) {
13921 		if (bp->b_flags & (B_PHYS | B_PAGEIO)) {
13922 			bp_mapin(bp);
13923 			remapped = 1;
13924 		}
13925 		bcopy(bp->b_un.b_addr, cont_bp->b_un.b_addr, bp->b_bcount);
13926 		if (remapped)
13927 			bp_mapout(bp);
13928 	}
13929 
13930 	return (cont_bp);
13931 }
13932 #else
13933 #ifdef __lock_lint
13934 static int
13935 st_bigblk_xfer_done(struct buf *bp)
13936 {
13937 	return (0);
13938 }
13939 #endif
13940 #endif
13941 
13942 static const char *eof_status[] =
13943 {
13944 	"NO_EOF",
13945 	"EOF_PENDING",
13946 	"EOF",
13947 	"EOT_PENDING",
13948 	"EOT",
13949 	"EOM",
13950 	"AFTER_EOM"
13951 };
13952 static const char *mode[] = {
13953 	"invalid",
13954 	"legacy",
13955 	"logical"
13956 };
13957 
13958 static void
13959 st_print_position(struct scsi_tape *un, const char *comment, tapepos_t *pos)
13960 {
13961 	ST_FUNC(ST_DEVINFO, st_print_position);
13962 	scsi_log(ST_DEVINFO, st_label, CE_NOTE,
13963 	    "%s Position data:\n", comment);
13964 	scsi_log(ST_DEVINFO, st_label, CE_CONT,
13965 	    "Positioning mode = %s", mode[pos->pmode]);
13966 	scsi_log(ST_DEVINFO, st_label, CE_CONT,
13967 	    "End Of File/Tape = %s", eof_status[pos->eof]);
13968 	scsi_log(ST_DEVINFO, st_label, CE_CONT,
13969 	    "File Number      = 0x%x", pos->fileno);
13970 	scsi_log(ST_DEVINFO, st_label, CE_CONT,
13971 	    "Block Number     = 0x%x", pos->blkno);
13972 	scsi_log(ST_DEVINFO, st_label, CE_CONT,
13973 	    "Logical Block    = 0x%"PRIx64, pos->lgclblkno);
13974 	scsi_log(ST_DEVINFO, st_label, CE_CONT,
13975 	    "Partition Number = 0x%x", pos->partition);
13976 }
13977