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