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