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